【发布时间】:2017-09-01 07:06:07
【问题描述】:
问题的详细讨论见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:en.cppreference.com/w/cpp/language/copy_assignment)。我猜你只是混合了你的方法。这应该看起来像这样“Point Point::operator=(Point& p)”或“double Point::operator=(Point& p)” - 不推荐。 -
我认为这是我见过的最滥用操作员的滥用行为。您需要编写
Point p; Point p2; double x = p = p2;以将p2的平方和转换为x,并且您将无法将一个Point分配给另一个Point。我不认为你真的想这样做。 -
@Spandy 你为什么要这样做?重载赋值运算符来做一些与赋值完全无关的事情只会让你的代码不必要地不可读而没有任何收获。如果你真的想让它成为一个运算符,至少使用一个不同于
operator=的运算符。 -
如果你真正想要的是
Point p; double d = p;,你可以创建一个转换运算符。不过,这仍然非常令人困惑。
标签: c++ class operator-overloading