2017-09-01 21 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