[英]How to use both member function and friend function operator overloading in same class
As per an assignment requirement,根据任务要求,
I am trying to implement prefix ++ and postfix ++ operator overloading both as member function and friend function 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
}
But when I trying to use prefix ++ or postfix ++ overloading it shows ambiguous error.但是当我尝试使用前缀 ++ 或后缀 ++ 重载时,它会显示模棱两可的错误。
dist d2(1, 900);
dist d3(3, 800);
/// these following lines showing ambiguous error
cout << d2++ << endl;
cout << ++d3 << endl;
Now,现在,
How can I use both type of operator overloading for same operator in same class file without getting any error.如何在同一个 class 文件中为同一个运算符使用两种类型的运算符重载而不会出现任何错误。
Most operators can be overloaded either as member or nonmember function.大多数运算符可以作为成员或非成员 function 重载。 Some operators (
=
[]
()
->
) can be overloaded only as members.某些运算符(
=
[]
()
->
)只能作为成员重载。 But you cannot have any oeprator both as a member and nonmember, specifically because it is unclear how to pick either one of them.但是您不能同时拥有任何操作员作为成员和非成员,特别是因为不清楚如何选择其中任何一个。
What the assignment wants is probably:任务想要的可能是:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.