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

Operator Overloading: Failed to return an object through *this

class“向量”声明如下:

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;
}

主要内容:

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

v3 收到意外值。

请告诉我哪一部分我执行错了,我该如何解决。 谢谢。

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

    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=() class 看起来像:

    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;
    }