Overloading comparison operators in derived class right private inheritance
I've got two classes here. A Base class:
class A
{
int x;
public:
A(int n):x(n){}
friend bool operator==(const A& left, const A& right)
{return left.x==right.x;}
};
and a derived class that inherits from A privately:
class B : private A
{
int y;
public:
B(int n,int x):A(x),y(n){}
friend bool operator==(const B& left, const B& right)
{
i开发者_JS百科f(left.y==right.y)
{/*do something here...*/}
else{return false;}
}
};
I know how to compare two instances of A: I just the member variables to each other. But how can I possibly compare instances of B? two instances could easily have different "x" members inside their associated "A" instances, but I have no idea how to compare those instances to each other.
You can cast the instances to A&
and use the equality operator for class A
:
if (static_cast<A&>(left) == static_cast<A&>(right)) {
// ...
}
精彩评论