views:

415

answers:

4
class mystring { 
private:
 string s;
public:
 mystring(string ss) { 
  cout << "mystring : mystring() : " + s <<endl; 
  s = ss;
 }
 /*! mystring& operator=(const string ss) { 
  cout << "mystring : mystring& operator=(string) : " + s <<endl;
  s = ss; 
  //! return this; 
  return (mystring&)this; // why COMPILE ERROR
 } */
 mystring operator=(const string ss) {
  cout << "mystring : mystring operator=(string) : " + s <<endl;
  s = ss;
  return *this;
 } 
 mystring operator=(const char ss[]) {
  cout << "mystring : mystring operator=(char[]) : " << ss <<endl;
  s = ss;
  return *this;
 }
};

mystring str1 =  "abc"; // why COMPILE ERROR
mystring *str2 = new mystring("bcd");

So the questiones are

  1. how to make a correct mystring& opeartor= overload?That is,how could I return a reference rather than a pointer?(could we tranfer between reference and pointer in C++?)

  2. how to make a correct mystring operator= overload?I thought the source code would work fine,but it turns out I still could not assign const char[] to mystring as if I didn't overload the operator=.

thanks.

+3  A: 
mystring& operator=(const string &ss) 
{
    cout << "mystring : mystring operator=(string) : " + s <<endl;
    s = ss;

    return *this; // return the reference to LHS object.
}
codaddict
A: 

As others pointed out, "string" has const char * type and you should overload assignment operator for it.

mystring& operator=(const char * s);

To get a reference from a pointer *this is suffice, no need to cast anything.

vava
Did Russel delete his answer?
Potatoswatter
Hm, yes, he did for some reason.
vava
`"string"` has type `const char[7]`, not `const char *`. As for the assignment operator, yes, it should be overloaded for `const char *`, which is the type the array will decay to.
AndreyT
+4  A: 

What you need is a 'conversion' constructor that takes a const char*:

mystring( char const* ss) {
  cout << "mystring : mystring(char*) ctor : " << ss <<endl;
  s = ss;
}

The line you're having a problem with:

mystring str1 =  "abc"; // why COMPILE ERROR

isn't really an assignment - it's an initializer.

Michael Burr
He needs both if he wants to perform assignment on preexisting objects.
Potatoswatter
A: 
 mystring& operator=(const string& ss) {
  cout << "mystring : mystring operator=(string) : " << s << endl;
  s = ss;

  return *this;
 } 
 mystring& operator=(const char* const pStr) {
  cout << "mystring : mystring operator=(zzzz) : " << pStr << endl;
  s = pStr;

  return *this;
 }
  • I added '&' to your strings so it returns a reference to 'this' and not a copy of it (it's good practice to do that for the input parameter too as you're then not uneccessarily making a copy of the input string),
  • I swapped a '+' to '<<' in line 2
  • and I altered your array to a const char const* pointer
queBurro