2016-11-07 110 views
0

我不知道我要問什麼取決於我正在使用的工具還是來自語言本身,但無論如何。C++/Eclipse cdt,避免實現相同的功能,但具有不同的簽名

我有一種情況,我有不同的簽名多次聲明「一種方法」。如:

class my_class { 
    public: 
     int getData(); 
     int getData() const; 
     my_class operator+(my_class&,my_class&); 
     my_class operator+(const my_class&, const my_class&) const; 
     //other operators, other functions etc with similar feature 
    private: 
     int data; 
}; 

正如你所想象的那樣,實現總是相同的,這只是簽名的問題。有沒有辦法避免寫兩次這樣的功能相同的實現?

在開始時,我認爲從類型轉換爲const類型已經執行,但顯然我錯了。

謝謝

回答

1
  1. 你重載未正確申報。類成員二元運算符只能使用一個參數,另一個則隱式地爲this。否則,你不能用中綴表示法來使用它。

  2. 您不需要兩個重載。運算符不應該改變操作數,所以const版本就足夠了。

所以這給我們留下了:

class my_class { 
    public: 
     int getData(); 
     int getData() const; 
     my_class operator+(const my_class&) const; 
     //other operators, other functions etc with similar feature 
    private: 
     int data; 
}; 

或者非會員版:

class my_class { 
    public: 
     int getData(); 
     int getData() const; 
     friend my_class operator+(const my_class&, const my_class&); 
     //other operators, other functions etc with similar feature 
    private: 
     int data; 
}; 

my_class operator+(const my_class&, const my_class&) { 
// code 
} 

至於getData()。它會回覆您的數據副本,並且我認爲它不會修改該實例。那麼const超負荷也就夠了。

+0

我對這個錯誤表示歉意。 – user8469759

+0

@ user8469759,無需道歉。我的回答對你有幫助嗎?那麼請考慮接受它。 – StoryTeller

+0

我正在爲運算符+編寫一些代碼,那麼「getData」呢? – user8469759

相關問題