Trying to overload the assignment operator in C++
Point%26amp; Point::operator=(const Point%26amp; p)
{
 if(this != %26amp;p)
 {
  delete [] label; //Deletes label
  label = new char(strlen (*(p.label)));
  strcpy(label, (*(p.label)));
  x = (*(p.x)); //Copies x.
  y = (*(p.y)); //Copies y
 }
 return *this; //Returns *this.
}
h:\point\point\point\point.cpp(64) : error C2664: 'strlen' : cannot convert parameter 1 from 'char' to 'const char *'
        Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
h:\point\point\point\point.cpp(64) : fatal error C1903: unable to recover from previous error(s); stopping compilation
With line 64 commented out:
h:\point\point\point\point.cpp(65) : error C2664: 'strcpy' : cannot convert parameter 2 from 'char' to 'const char *'
        Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
h:\point\point\point\point.cpp(66) : error C2440: '=' : cannot convert from 'double' to 'double *'
h:\point\point\point\point.cpp(67) : error C2440: '=' : cannot convert from 'double' to 'double *'
Help overloading assignment operator in C++?
label = new char(strlen (*(p.label)));
strcpy(label, (*(p.label)));
x = (*(p.x)); //Copies x.
y = (*(p.y)); //Copies y
The code above replace with
label = new char(strlen ((p.label)));
strcpy(label, ((p.label)));
x = p.x; //Copies x.
y = p.y; //Copies y
Reply:????
Reply:Ok, The line 
Point%26amp; Point::operator = (const Point%26amp; p)
This means that your argument to the function is passed by reference, and returns a reference.
A reference argument is used like a regular argument, no special treatment required.
I believe the assignment operator is redefined as
Point%26amp; Point::operator = (const Point%26amp; p)
The complete function would be
Point%26amp; Point::operator = (const Point%26amp; p)
{
   if (this == %26amp;p)
      return *this;
   char *temp;
   double dx, dy;
   temp = new char[strlen(p.label) + 1];
   strcpy(temp, p.label);
   dx = p.x;
   dy = p.y;
   x = dx;
   y = dy;
   delete label;
   label = new char[strlen(temp) + 1];
   strcpy(label, temp);
   delete temp;
   return *this;
}
Subscribe to:
Post Comments (Atom)
 
No comments:
Post a Comment