How do I overload the operator "=" ?

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) {
	return this;			
	}
};
int main() {
	Str s = "s"; //conversion from ´const char [2]´to non-scalar type ´Str´requested
}
string str = "Hello world";

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( const char * ) { /* some code */ }

Of cource if this constructor will not be declared as explicit it would be not bad to declare a corresponding assignment operator

1
2
3
4
5
Str & operator =( const char * )
{
   /* some code */
   return ( *this );
}


Though it is enogh to have only the conversion consttructor.
Last edited on
Thank you for the example! I didn´t know it was called conversion constructor. I will read more about that now! :-)
Topic archived. No new replies allowed.