I am reading about operator overloading and have a question about the standard string class. How is it possible to just write: string str = "Hello world";?
How can I overload the = operator so I can use it like the line above?
1 2 3 4 5 6 7 8 9
class Str {
public:
Str *operator = (char *c) {
returnthis;
}
};
int main() {
Str s = "s"; //conversion from ´const char [2]´to non-scalar type ´Str´requested
}
It is not an assignment operator. In the example above a conversion constructor is used, that is a constructor that accepts as the first argument an object of type
const char[]
If you want to achieve the same effect then declare the following conversion constructor
Str( constchar * ) { /* some code */ }
Of cource if this constructor will not be declared as explicit it would be not bad to declare a corresponding assignment operator