I am currently learning C++. But now I wrote some code to overload operatos. The first operator- is not working and returns "No access to private members ..."?! The second operator+ is working properly.
I really can not spot my misstake here ... hopefully you can help me out.
class burrito
{
burrito operator-(const burrito& b);
friend burrito operator+(burrito& a, burrito& b);
private:
staticint varstat;
int x;
int y;
public:
burrito();
burrito(int x, int y);
staticint getstat();
int getx();
int gety();
void setx(int x);
void sety(int y);
};
Members of a class are private by default.
Members of a struct are public by default.
Therefore, the burrito operator-(const burrito& b); is private.
The main cannot access private members.
The friend burrito operator+(burrito& a, burrito& b); is not a declaration of a member.
It just tells that a standalone function burrito operator+(burrito& a, burrito& b); has access to all members of burrito.
It does not need to be a friend, because it uses public interface of burrito (get*, set*).
As friend, it can:
1 2 3 4
burrito operator+(burrito& a, burrito& b) {
burrito ergebnis( a.x + b.x, a.y + b.y );
return ergebnis;
}
It is better to have non-friend non-members.
A canonical approach to these operators is to have operators += and -= as members and
operators + and - as non-friend non-members. Implement latter with former. For example:
1 2 3 4
burrito operator+(burrito a, const burrito& b) {
a += b;
return a;
}