我当时在做一门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> =,但这不是重点,这里的比较只是一个例子。
免责声明:至少在进行比较时,最好不要在真实代码中完成此类操作。这只是一些C ++构造的示例使用。
方案1:静态分派。
class A{
int a;
public:
A(int a) : a(a) {}
friend bool operator<(A& x, A& y){ return x.a < y.a; }
};
class B: public A{
int b;
public:
B(int a, int b) : A(a), b(b) {}
friend bool operator<(B& x, B& y){ return x.b < y.b; }
};
此代码根据A和B对象的静态类型对其进行比较。因此,如果您有:
B b(0, 42);
A& a = b;
a
会像A
比较中一样 该系统基于操作员超载。
变体2:动态调度。
class A;
class B;
class A{
int a;
public:
A(int a) : a(a) {}
virtual ~A() {}
bool operator<(A& t){ return t.compare(*this); }
protected:
virtual bool compare (A& t);
virtual bool compare (B& t);
};
class B: public A{
int b;
public:
B(int a, int b) : A(a), b(b) {}
protected:
bool compare (A& t) override;
bool compare (B& t) override;
};
bool A::compare(A& t) { return t.a < a; }
bool A::compare(B& t) { return t.a < a; }
bool B::compare(A& t) { return A::compare(t); }
bool B::compare(B& t) { return t.b < b; }
该代码根据A和B对象的动态类型对其进行比较。因此,如果您有:
B b(0, 42);
A& a = b;
a
会像B
比较中一样 该系统基于双重动态调度,有时也称为访客模式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句