如何超载分配运算符,该操作员总计两个实例变量
How do overload an assignment operator that sums two instance variable of a class?
此链接中显示了该问题的详细讨论。我正在尝试总结两个在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();
您切勿以这种方式超载分配运算符。阅读您的代码的人会感到困惑,因为分配通常意味着..将值分配给对象。
而是创建一个类似的方法
double Point::LengthSquared() { return getSqX() + getSqY(); }
分配操作员应具有以下接口:
Point& operator=(const Point& other);
或
Point& operator=(const AnotherType& other);
允许其他类型的分配。
您正在滥用任务操作员。使用常规方法。
相关文章:
- 我可以创建一个包含两个变量的 for 循环,但时间复杂度仍然为 O(n) 吗?
- 命令行参数,cant 或两个变量
- 在 for 循环中更新两个变量时遇到问题C++
- C++ 编译时在两个变量之间交替
- C++ 如何在包含两个变量的结构中存储与变量不同数量的值?
- 为什么一个接一个声明的两个变量在内存中不相邻?
- 为什么动态分配的两个变量的内存位置不是连续的?
- 是否可以在C++中使用宏交换两个变量的出现?
- 计算机如何分配两个变量,我们如何计算两个变量之间的距离?
- 正确证明C 中的两个变量合理(我想将它们视为一个变量)
- 可视C 编译器将相同的存储位置提供给两个变量
- 尝试使用 {} 和 std::make_pair() 交换两个变量时的行为不同
- 在rootframework中的根文件中编写两个变量
- 最短路径,带有两个变量
- 加入两个变量和LCD打印
- 在循环中声明两个变量以逆转字符串?在C 中
- 具有两个变量的"for"循环,一个变量每次迭代递增,每隔一次迭代递增
- 如何在C++中使用一个类中两个变量的值
- 仅在C 中的一个变量上,两个变量函数的数值集成(使用数值配方库)
- 如何在我存储的两个变量之间生成随机数