[英]How to use both member function and friend function operator overloading in same class
根據任務要求,
我正在嘗試在同一個 class 中實現前綴 ++ 和后綴 ++ 運算符重載作為成員 function 和朋友 function。
class dist {
private:
int kMeter;
int meter;
public:
// postfix
dist operator++(int unused) {
dist dd = *this;
(this -> meter)++;
return dd;
}
// prefix
dist operator++() {
++(this -> meter);
return *this;
}
dist(int k = 0, int m = 0) {
kMeter = k;
meter = m;
}
void print();
int getMeter() const { return meter; }
int getKMeter() const { return kMeter; }
friend dist operator++(dist& d, int unused); //postfix
friend dist operator++(dist& d); // prefix
};
dist operator++(dist& d, int unused) { // postfix friend func
dist dd = d; // copy the old value into dd
d.meter++;
return dd; // return the original value of d
}
dist operator++(dist& d) { // friend prefix ++
++d.meter;
return d; // return the final value of d
}
但是當我嘗試使用前綴 ++ 或后綴 ++ 重載時,它會顯示模棱兩可的錯誤。
dist d2(1, 900);
dist d3(3, 800);
/// these following lines showing ambiguous error
cout << d2++ << endl;
cout << ++d3 << endl;
現在,
如何在同一個 class 文件中為同一個運算符使用兩種類型的運算符重載而不會出現任何錯誤。
大多數運算符可以作為成員或非成員 function 重載。 某些運算符( =
[]
()
->
)只能作為成員重載。 但是您不能同時擁有任何操作員作為成員和非成員,特別是因為不清楚如何選擇其中任何一個。
任務想要的可能是:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.