运算符重载:无法通过*this返回对象



类"矢量";声明如下:

class Vector
{
private:
float *arr;
int currentIndex;
int arrSize;
public:
Vector();
Vector(int size);
Vector(const Vector& V);
~Vector();

float length();
Vector normalize();
Vector operator +(const Vector &v);
Vector operator =(const Vector &v);
Vector operator -(const Vector &v);
};

我定义了";运算符+";以及";运算符=";如下所示:

Vector  Vector::operator +(const Vector &v)
{
for (int i = 0; i < arrSize; i++)
{
arr[i] += v.arr[i];
}

return *this;
}
Vector  Vector::operator=(const Vector &v)
{
if (this != &v)//to avoid case "v = v"
{
arrSize = v.arrSize;
currentIndex = v.currentIndex;
delete [] arr;
arr = new float [arrSize];
for (int i = 0; i < arrSize; i++)
{
arr[i] = v.arr[i];
}
}
return *this;
}

main:

//...declared v1, v2 and v3...
v3 = v1 + v2;
cout << v3 << endl;

v3接收到意外值。

请告诉我我错误地执行了哪个部分,以及如何修复它。谢谢

您正在尝试实现运算符+((,因此不想在内存中为该对象编辑任何内容(这将是运算符+=((的工作(。你可以这样做:

Vector Vector::operator+(const& Vector v) //Note it's Vector, not Vector&
{
//You probably want to verify that the vectors are the same size?
assert(arrSize == v.arrSize); //You can do this some other way as well

Vector out = Vector(arrSize); //Create a new object on the heap to return
for (int i = 0; i < arrSize; i++)
out.arr[i] = arr[i] + v.arr[i]; //Do the addition
return out;
}

然后你的operator=((类看起来像:

Vector& Vector::operator=(const& Vector v) //Note the return type of Vector&
{
if (this != &v) //This check is probably superflous
{
arrSize = v.arrSize;
currentIndex = v.currentIndex;
delete[] arr;
arr = new float[arrSize];
for (int i = 0; i < arrSize; i++)
arr[i] = v.arr[i];
}
return *this;
}

最新更新