【问题标题】:How do overload an assignment operator that sums two instance variable of a class?如何重载对类的两个实例变量求和的赋值运算符?
【发布时间】: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 &amp; class_name :: operator= ( class_name )(SRC:en.cppreference.com/w/cpp/language/copy_assignment)。我猜你只是混合了你的方法。这应该看起来像这样“Point Point::operator=(Point&amp; p)”或“double Point::operator=(Point&amp; p)” - 不推荐。
  • 我认为这是我见过的最滥用操作员的滥用行为。您需要编写Point p; Point p2; double x = p = p2; 以将p2 的平方和转换为x,并且您将无法将一个Point 分配给另一个Point。我不认为你真的想这样做。
  • @Spandy 你为什么要这样做?重载赋值运算符来做一些与赋值完全无关的事情只会让你的代码不必要地不可读而没有任何收获。如果你真的想让它成为一个运算符,至少使用一个不同于operator= 的运算符。
  • 如果你真正想要的是Point p; double d = p;,你可以创建一个转换运算符。不过,这仍然非常令人困惑。

标签: c++ class operator-overloading


【解决方案1】:

您不应该以这种方式重载赋值运算符。阅读您的代码的人会感到困惑,因为赋值通常意味着 .. 为对象赋值。

相反,创建一个这样的方法

double Point::LengthSquared() { return getSqX() + getSqY(); }

【讨论】:

  • 我需要调用 FFTfile[j].LengthSquared() 来获得平方和吗?
  • 是的,就是这个意思。
  • 我收到以下错误:“class std::vector”没有名为“LengthSquared()”的成员。错误在这一行 temp=FFTfile[j].LengthSquared();
  • 您忘记了索引“[i]”。你的意思可能是 temp = FFTfile[i][j].LengthSqueared();
【解决方案2】:

赋值运算符应具有以下接口:

Point& operator=(const Point& other);

Point& operator=(const AnotherType& other);

允许其他类型的分配。

您正在滥用赋值运算符。使用常规方法。

【讨论】:

  • 返回 Point 类型的对象有什么帮助呢?我可以将“操作=”的输出分配给浮点变量吗?
  • 重点是,您不应该为此使用赋值运算符。创建一个常规方法。同行给你举个例子。LengthSquared()
  • @Spandy 看起来如何(将operator= 的输出分配给浮点数)。你想要这样:float f = pointA = pointB 吗?因为不要那样做,它完全不可读和令人困惑。此外,您不能像那样重载=,如果绝对必须使用不同的运算符。
猜你喜欢
  • 1970-01-01
  • 2011-01-26
  • 1970-01-01
  • 2017-03-16
  • 2016-01-04
  • 2017-10-07
  • 1970-01-01
  • 2013-02-03
相关资源
最近更新 更多