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 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.
Most operators can be overloaded either as member or nonmember 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: