C++ 这种加法有什么问题?

C++ 这种加法有什么问题?,c++,class,methods,console-application,C++,Class,Methods,Console Application,这是Vector类的公共继承中的方法声明: Vector Addition(Vector a, Vector b); 下面是类外实现: Vector Vector::Addition(Vector a, Vector b) { Vector temp = *this; temp.x=a.x+b.x; temp.y=a.y+b.y; return temp; } 当我在主函数中执行此操作时: Vector c(0,0),a(0,0),b(0,0); c=Addi

这是Vector类的公共继承中的方法声明:

Vector Addition(Vector a, Vector b);
下面是类外实现:

Vector Vector::Addition(Vector a, Vector b)
{
    Vector temp = *this;
    temp.x=a.x+b.x;
    temp.y=a.y+b.y;
    return temp;
}
当我在主函数中执行此操作时:

Vector c(0,0),a(0,0),b(0,0);
c=Addition(a,b);
我得到一个错误:标识符添加未定义。请帮忙

c=Addition(a,b);
告诉编译器调用函数独立函数。您提供了一个成员函数,而不是独立函数,因此编译器无法找到任何成员函数,并且会出现问题

您需要提供一个独立的函数。

由于您的加法函数是Vector的一个成员,因此必须这样调用它:

c = Vector::Addition(a, b);

请注意,第一个函数要求加法函数是静态的,这意味着它不会在函数体中的具体实例上运行:

static Vector Addition(Vector a, Vector b);
但是你不能访问一个this指针,所以你必须默认构造temp,而不是复制一个副本,顺便说一句,由于你覆盖了x和y,这个副本是未使用的

第二个使用左侧操作数作为签名中实现no a中的this指针

Vector Addition(Vector b)
{
    Vector temp = *this;
    temp.x += b.x;
    temp.y += b.y;
    return temp;
}

注意,C++中也可以重载运算符。为此,请定义一个名为operator+的非静态成员函数,该函数接受第二个实例。第一个实例是函数中的this指针,它将是左侧操作数:

Vector operator+(const Vector &other) const;
实施一种可能性:

Vector Vector::operator+(const Vector &other)
{
    Vector temp = *this;
    temp.x += other.x;
    temp.y += other.y;
    return temp;
}
在向量内声明了加法。正确的方法是

1将加法作为全局函数。这将涉及从Vector类中获取加法的定义。这样看起来

Vector Addition(/*parameters*/) { /* implementation */ }
 class Vector{
 static Vector Addition(/* arguments */);
}

Vector Vector::Addition(/*arguments*/) {/*implementation*/}
2使用static关键字使Addition static,并使用代码c=Vector::Additiona,b调用它

代码看起来像

Vector Addition(/*parameters*/) { /* implementation */ }
 class Vector{
 static Vector Addition(/* arguments */);
}

Vector Vector::Addition(/*arguments*/) {/*implementation*/}

如果你想以这种方式使用加法,它必须是一个自由函数,而不是一个方法。我不确定它提供了什么回报{a.x+b.x,a.y+b.y};,不过,有一个合适的构造函数。还有一个问题。为什么必须在重载运算符+的括号中写入常量?如果只写向量运算符+向量&其他,这是错误的吗@A6Tech,你没有修改它,为什么要使它非常量?它只是限制了您可以传入的内容,无论是常量对象还是临时对象。请注意,另一种流行的方法是使用自由函数,按值取左侧,并对其调用运算符+=。@chris我想您已经解释了括号中的常量。但是它们后面的那一个呢?@A6Tech,这意味着它不能修改调用对象save mutable members,因此可以使用+。