解决
我想重载二元加法运算符(operator+
)。我的编译器(Borland Builder)说操作符重载定义存在声明语法错误。
这是我的代码:
class Foo{
public:
double x,y,z;
Foo();
Foo(double xi, double yi, double zi) : x(xi), y(yi), z(zi) {};
friend Foo operator+(const Foo &a, const Foo &b);
} // Here is the error - no closing ';'
Foo operator+(const Foo &a, const Foo &b) //Error E2141 Declaration syntax error
{
return Foo(a.x + b.x, a.y + b.y, a.z + b.z);
}

我和here做了同样的事。为什么我会收到编译器错误?
示例,寻求对答案的评论中的问题
Foo& operator*(const double &b, Foo& foo){
foo.x*=t;
foo.y*=t;
foo.z*=t;
return foo;
}
.
int main(){
Foo temp;
Foo bar = 4*temp;
return 0;
}
答案 0 :(得分:-1)
样品:
#include <iostream>
class Foo{
public:
double x,y,z;
Foo();
Foo(double xi, double yi, double zi) : x(xi), y(yi), z(zi) {};
Foo operator + (const Foo &a) const;
};
Foo Foo::operator + (const Foo &a) const {
return Foo(a.x + this->x, a.y + this->y, a.z + this->z);
}
int main() {
Foo f1(1.0, 1.1, 1.2);
Foo f2(1.6, 1.1, 1.2);
Foo f3 = f1 + f2;
std::cout << "f3.x=" << f3.x << std::endl;
return 0;
}