2017-09-01 67 views
-2

该问题的详细讨论如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(); 
+0

嗨,查看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

+0

我认为这是我见过的最滥用的操作员滥用行为。你需要写'Point p;点p2; double x = p = p2;'将p2的正方形的总和变为'x',并且您将无法将一个'Point'分配给另一个。我不认为你真的想这样做。 – molbdnilo

+0

@Spandy你为什么要这么做?重载赋值运算符以完成与赋值完全无关的任何事情只会让您的代码在不获取任何内容的情况下无法读取。 如果你确实真的希望这是一个运算符,至少使用一个不同于'operator ='的运算符。 – Zinki

回答

0

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

取而代之的是,创建一个方法是这样

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

我需要调用FFTfile [j] .LengthSquared()来获得平方和吗? – Spandy

+0

是的,这是主意。 –

+0

我得到以下错误:'class std :: vector '没有名为'LengthSquared()'的成员。错误在这一行temp = FFTfile [j] .LengthSquared(); – Spandy

0

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

Point& operator=(const Point& other); 

Point& operator=(const AnotherType& other); 

以允许其他类型的任务。

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

+0

如何返回Point类型的对象帮助?我能够将“操作=”的输出分配给浮点变量吗? – Spandy

+1

重点是,你不应该使用赋值操作符。创建一个常规的方法。 Peer给了你一个例子.LengthSquared() –

+1

@Spandy甚至会看起来如何(将'operator ='的输出赋值给float)。 你想要它像这样: 'float f = pointA = pointB'?因为不这样做,它完全不可读和混乱。另外,你不能像这样重载'=',如果你绝对必须使用不同的操作符。 – Zinki