派生类中重载比较运算符右私有继承
我在这里有两节课。基类:
class A
{
int x;
public:
A(int n):x(n){}
friend bool operator==(const A& left, const A& right)
{return left.x==right.x;}
};
以及私有地从 A 继承的派生类:
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)
{
if(left.y==right.y)
{/*do something here...*/}
else{return false;}
}
};
我知道如何比较 A 的两个实例:我只是相互比较成员变量。但我怎么可能比较 B 的实例呢?两个实例可以很容易地在其关联的“A”实例中具有不同的“x”成员,但我不知道如何将这些实例相互比较。
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)
{
if(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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将实例强制转换为
A&
并对class A
使用相等运算符:You can cast the instances to
A&
and use the equality operator forclass A
: