Operator overloading as friend function error

时间:2016-04-25 09:35:50

标签: c++ operator-keyword

I'm trying to use + to add 2 vector (mathematical vector). Here's my code:

class Vector{
    double v[Max_size];
    int dim;
public:
    int getDim() const;
    Vector();
    Vector(int n);
    Vector(const Vector& a);
    Vector add(const Vector&b);
    friend Vector operator+(Vector summand1, Vector summand2);
};

Operator overloading:

Vector operator+(Vector summand1, Vector summand2){
    int dim1 = summand1.getDim();
    int dim2 = summand2.getDim();
    assert(dim1 == dim2);
    Vector sum(dim1);
    int i;
    for(i = 0; i < dim1; i++){
        sum.v[i] = summand1.v[i] + summand2.v[i];
    }
    return sum;
}

And how I use it:

Vector m = v+t;

When I run the code, it always shows that m is (0,0) (2D vector), which is the default value generated by the constructor. What's wrong with it? Thanks!

1 个答案:

答案 0 :(得分:1)

您的复制构造函数:

Vector::Vector(const Vector& a){
    dim = a.dim;
    Vector(dim);
}

正确设置dim成员的值,但没有其他副作用。

您应该拥有以下代码的变体:

Vector::Vector(const Vector& a) : dim(a.dim) {
    std::copy(std::begin(a.v), std::end(a.v), v);
}

这实际上会复制参数中存在的数据,您将看到代码的正确行为:

// Copy constructor called here, but did not correctly copy the data before.
Vector m = v + t;

为了更好(我希望更简单,更安全)Vector类,如果您可以访问至少符合C ++ 11的编译器,则可以编写:

class Vector{
    std::array<double, Max_size> v; // Note the std::array here.
    int dim;
public:
    int getDim() const;
    Vector();
    Vector(int n);
    Vector(const Vector& a);
    Vector add(const Vector&b);
    friend Vector operator+(Vector summand1, Vector summand2);
};

std::array将处理所有事情,前提是您编写了这样的复制构造函数:

Vector::Vector(const Vector& a) : v(a.v), dim(a.dim) {

}

或者,更好的是,您可以让编译器生成具有相同行为的复制构造函数。