Answer the question
In order to leave comments, you need to log in
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"; /// Работает нормально
}
#include<iostream>
class MyExpirementalString
{
public:
MyExpirementalString(const char *const cstr)
{
std::cout<<cstr<<std::endl;
}
};
int main()
{
std::string str0="Hello"; /// Все нормально
MyExpirementalString str="Hello"; /// Все нормально
}
Answer the question
In order to leave comments, you need to log in
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.
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)
It is desirable to declare a constructor with one parameter explicit.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question