Shapeの基本タイプへのポインターがいくつかあります。==演算子を使用してこれらのオブジェクトを比較したいと思います。オブジェクトが異なる派生型である場合、==演算子は明らかにfalseを返す必要があります。ただし、それらが同じ派生型である場合は、派生型のメンバーを比較する必要があります。
C ++ RTTIの使用は悪い習慣であり、まれで本質的な状況でのみ使用する必要があることを読みました。私が見る限り、この問題はRTTIを使用せずに一般的に解決することはできません。オーバーロードされた各==演算子は、typeidをチェックする必要があり、それらが同じである場合は、dynamic_castを実行してメンバーを比較します。これは一般的なニーズのようです。この問題にはある種のイディオムがありますか?
#include <iostream>
using namespace std;
class Shape {
public:
Shape() {}
virtual ~Shape() {}
virtual void draw() = 0;
virtual bool operator == (const Shape &Other) const = 0;
};
class Circle : public Shape {
public:
Circle() {}
virtual ~Circle() {}
virtual void draw() { cout << "Circle"; }
virtual bool operator == (const Shape &Other) const {
// If Shape is a Circle then compare radii
}
private:
int radius;
};
class Rectangle : public Shape {
public:
Rectangle() {}
virtual ~Rectangle() {}
virtual void draw() { cout << "Rectangle"; }
virtual bool operator == (const Shape &Other) const {
// If Shape is a Rectangle then compare width and height
}
private:
int width;
int height;
};
int main() {
Circle circle;
Rectangle rectangle;
Shape *Shape1 = &circle;
Shape *Shape2 = &rectangle;
(*Shape1) == (*Shape2); // Calls Circle ==
(*Shape2) == (*Shape1); // Calls Rectangle ==
}