Question:
Help overloading assignment operator in C++?
gramps199
2007-10-05 07:32:40 UTC
Trying to overload the assignment operator in C++

Point& Point::operator=(const Point& p)
{
if(this != &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 *'
Four answers:
Ivan D
2007-10-05 08:10:33 UTC
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
anonymous
2007-10-05 08:04:49 UTC
Ok, The line

Point& Point::operator = (const Point& 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& Point::operator = (const Point& p)

The complete function would be

Point& Point::operator = (const Point& p)

{

if (this == &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;

}
?
2016-10-06 07:44:04 UTC
you may declare the class yet with diverse information kinds. this is how the compiler is familiar with what functionality to apply. That way once you declare the class of a particular type, it purely makes use of the class matching the information type. consequently, overloaded.
moto_x_freek
2007-10-05 07:35:28 UTC
????


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...