[英]C++/Eclipse cdt, avoid to implement the same function but with different signature
我不知道我要問的問題取決於我使用的工具還是語言本身,但是無論如何。
我遇到這樣的情況,我用不同的簽名多次聲明了“一個方法”。 如:
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類型的轉換,但是顯然我錯了。
謝謝
您的重載未正確聲明。 類成員二進制運算符只能采用一個參數,另一個則隱式為this
。 否則,您不能將其與中綴符號一起使用。
您不需要兩個重載。 運算符不應更改操作數,因此僅使用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
重載就足夠了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.