该问题的详细讨论如this link所示。我正在总结在类Point
中定义的两个实例变量,并将其分配给另一个变量temp
。如何重载一个赋值类的两个实例变量的赋值运算符?
class Point{
public:
double x;
double y;
friend istream& operator>>(istream& input, Point& p);
double operator=(Point& p);
double getSqX(void);
double getSqY(void);
double LengthSquared(void);
};
double Point::getSqX(void){
return pow(x,2);}
double Point::getSqY(void){
return pow(y,2);}
double Point::LengthSquared(){ return getSqX() + getSqY(); }
istream& operator>>(istream& input, Point& p){
... // over load the >> operator
return input;
};
int main(){
double temp;
vector<vector<Point> > FFTfile= some function that loads data();
for (int i = 0; i < FFTfile.size(); i++){
for (int j = 0; j < FFTfile[i].size(); j++){
temp=FFTfile[j].LengthSquared();
}
}
return(0);
}
编辑:
基础上提出的建议,我创建了一个方法LengthSquared(),但我仍然得到以下错误:
error: 'class std::vector<Point>' has no member named 'LengthSquared' temp=FFTfile[j].LengthSquared();
嗨,查看Peer和Martin的答案,同样为了清楚起见,C++中的赋值运算符看起来像这样:'class_name&class_name :: operator =(class_name)'(SRC:http://en.cppreference.com/W/CPP /语言/ copy_assignment)。我猜你只是混淆了你的方法。这应该看起来像这样:“Point Point :: operator =(Point&p)'”或“double Point :: operator =(Point&p)'” - 不推荐。 – Guillotine
我认为这是我见过的最滥用的操作员滥用行为。你需要写'Point p;点p2; double x = p = p2;'将p2的正方形的总和变为'x',并且您将无法将一个'Point'分配给另一个。我不认为你真的想这样做。 – molbdnilo
@Spandy你为什么要这么做?重载赋值运算符以完成与赋值完全无关的任何事情只会让您的代码在不获取任何内容的情况下无法读取。 如果你确实真的希望这是一个运算符,至少使用一个不同于'operator ='的运算符。 – Zinki