问题描述
$
b$ b
在C ++中,派生类如何以有意义的方式覆盖基类的等式测试?
例如,基本类A.类B和C从A派生。现在给定两个A对象的两个指针,我可以测试它们是否相等(包括任何子类数据)?
class A {
public:int data;
};
class B:public A {
public:float more_data; bool something_else;
};
class C:public A {
public:double more_data;
};
A * one = new B;
A * two = new B;
A * three = new C;
//如何测试一个,两个或三个是否等于
//包括任何派生类数据?
有干净的方法吗?
谢谢!
对公共非虚拟/非公共虚拟成语及其优点的简要描述,而不是在哪里。 有一个好的描述。
以下是如何将它应用于op ==:
struct A {
virtual〜A(){}
int a;
friend
bool operator ==(A const& lhs,A const& rhs){
return lhs.equal_to(rhs);
}
// http://en.wikipedia.org/wiki/Barton-Nackman_trick
//以简化的形式在这里使用
protected:
virtual equal_to(A const& other)const {
return a == other.a;
}
};
struct B:A {
int b;
protected:
virtual equal_to(A const& other)const {
if(B const * p = dynamic_cast< B const *>(& other)){
return A :: equal_to(other)&& b == p-> b;
}
else {
return false;
}
}
};
struct C:A {
int c;
protected:
virtual equal_to(A const& other)const {
if(C const * p = dynamic_cast< C const *>(& other)){
return A :: equal_to(other)&& c == p-> c;
}
else {
return false;
}
}
};
In C++, how can derived classes override the base class equality test in a meaningful way?
For example, say I have a base class A. Classes B and C derive from A. Now given two pointers to two A objects, can I test if they are equal (including any subclass data)?
class A {
public: int data;
};
class B : public A {
public: float more_data; bool something_else;
};
class C : public A {
public: double more_data;
};
A* one = new B;
A* two = new B;
A* three = new C;
//How can I test if one, two, or three are equal
//including any derived class data?
Is there a clean way of doing it? What's my best bet?
Thanks!
I remember reading a succinct description of the public-non-virtual/non-public-virtual idiom and its advantages, but not where. This wikibook has an okay description.
Here is how you apply it to op==:
struct A {
virtual ~A() {}
int a;
friend
bool operator==(A const& lhs, A const& rhs) {
return lhs.equal_to(rhs);
}
// http://en.wikipedia.org/wiki/Barton-Nackman_trick
// used in a simplified form here
protected:
virtual equal_to(A const& other) const {
return a == other.a;
}
};
struct B : A {
int b;
protected:
virtual equal_to(A const& other) const {
if (B const* p = dynamic_cast<B const*>(&other)) {
return A::equal_to(other) && b == p->b;
}
else {
return false;
}
}
};
struct C : A {
int c;
protected:
virtual equal_to(A const& other) const {
if (C const* p = dynamic_cast<C const*>(&other)) {
return A::equal_to(other) && c == p->c;
}
else {
return false;
}
}
};
这篇关于C ++中派生类的平等测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!