【发布时间】:2018-06-13 13:11:46
【问题描述】:
我正在学习 Python 课程,突然出现了使用父类覆盖函数来比较父类和子类的想法。基本上:
class A(object):
def __init__(self,a):
self.a = a
def __lt__(self,other):
return self.a < other.a
class B(A):
def __init__(self,a,b):
self.a = a
self.b = b
def __lt__(self,other):
return self.b < other.b
a = A(2)
b = B(1,3)
print(a < b)
#print(b < a) # AttributeError: 'A' object has no attribuite 'b'
print(A.__lt__(b,a)) # so we call this instead
现在,我想在 C++ 中做同样的事情
class A{
int a;
public:
A(int a) : a(a) {}
bool operator<(A t){ return a < t.a; }
};
class B: public A{
int b;
public:
B(int a, int b) : A(a), b(b) {}
bool operator<(B t){ return b < t.b; }
};
int main()
{
A a(2);
B b(3,1);
std::cout << (a < b) << std::endl;
//std::cout << (b < a); // error, A has no b attribute
//std::cout << A::operator<(dynamic_cast<A&>(b),a); // basically what I would like to happen
std::cout << a.operator<(dynamic_cast<A&>(b)) << std::endl; // here I would like to reverse a and b
return 0;
}
总得有个办法吧,不知道是不是对C++中的方法缺乏了解。
我知道我可以只重载 operator>=,但这不是重点,比较只是这里的一个示例。
【问题讨论】:
-
如果您比较两个确实是
B对象的A&对象,您期望会发生什么? IE。B x; A& y = x; return y < y;?它应该比较a或b的每个成员吗? -
如果我将
x投射到A&上,那么它应该通过A类中定义的operator<来比较它们,所以通过a属性来比较它们。其实你的问题帮我搞定了,我应该简单地将B对象投射到A&上,然后调用它的操作员,即:dynamic_cast<A&>(x) < y -
进行这样的二进制操作在大多数情况下是没有意义和危险的。你可以实现你想要玩弄的东西并探索 C++ 是如何工作的,但是如果你用真实的代码来做,你会后悔的。只是不要。请给我们一个真实世界的例子,说明您正在尝试做什么。也许一个更好的设计选择是为了。
-
这是一个纯粹的理论问题,因为同样的事情在 Python 中可以很容易地实现。