D
D
Daniil Demidko2016-02-12 11:36:33
C++ / C#
Daniil Demidko, 2016-02-12 11:36:33

Why can't I completely overload the = operator?

Here is the code.

#include<iostream>
class MyExpirementalString
{
public:
    void operator=(const char *const cstr)
    {
        /// Проверяем работу перегруженного оператора =
        std::cout<<cstr<<std::endl;
    }
};
int main()
{
    std::string str0="Hello"; /// Все нормально

    MyExpirementalString str="Hello"; /// Ошибка. Почему?

    /// Тогда как
    str="Hello"; /// Работает нормально
}

Why is it not possible to overload the = operator so that it works immediately when a variable is created?
MyExpirementalString s="str";
Update:
Fixed the class like this:
#include<iostream>
class MyExpirementalString
{
public:
     MyExpirementalString(const char *const cstr)
    {
        std::cout<<cstr<<std::endl;
    }
};
int main()
{
    std::string str0="Hello"; /// Все нормально

    MyExpirementalString str="Hello"; /// Все нормально
}

But what's going on here? Pros blow your mind

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
MiiNiPaa, 2016-02-12
@Daniro_San

Mistake. Why?
Because you are not calling the assignment operator, but doing a copy-initializtion. A simple rule can help you: all actions performed when declaring a variable call the constructor.

R
res2001, 2016-02-12
@res2001

In the first case with an error - the assignment operator has a different signature - there should be a reference there. In your case, something like this:
void operator=(const char *& cstr)
The compiler does not find a suitable assignment operator, hence the error.
In the second case, you made a suitable constructor and the compiler took advantage of it. But it's better to define this constructor as a copy constructor:
MyExpirementalString(const char *& cstr)

N
Nikolai Romanovich, 2016-02-12
@MikalaiR

It is desirable to declare a constructor with one parameter explicit.

0
014, 2016-02-13
@014

Write an explicit copy constructor:

MyExpirementalString(MyExpirementalString & cstr)
    {
        std::cout<<cstr<<std::endl;
    }

and a constructor with a pointer to char will no longer work for you. I do, and I don't understand why.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question