如何超载分配运算符,该操作员总计两个实例变量

How do overload an assignment operator that sums two instance variable of a class?

本文关键字:两个 变量 实例 操作员 何超载 超载 分配 运算符      更新时间:2023-10-16

此链接中显示了该问题的详细讨论。我正在尝试总结两个在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);

允许其他类型的分配。

您正在滥用任务操作员。使用常规方法。