如何询问对象是否属于类x?

Gru*_*ear 2 c++ object

所以我有Shape.h,Rectangle.h,Circle.h和main.cpp.

Shape.h得到:

class Shape{
public:
    Shape() {};
    ~Shape() { cout << "Destroy Shape."; };

    virtual double getArea() = 0;
    virtual double getCircumference() = 0;
};
Run Code Online (Sandbox Code Playgroud)

矩形和圆形各自的代码.

现在在main.cpp我做

Shape* newRectangle= new Rectangle(4, 8);
Shape* newCircle= new Circle(10);
Run Code Online (Sandbox Code Playgroud)

到目前为止,所有罚款和花花公子.这是我难倒的地方.我知道我要做什么,我只是不知道怎么做.

我正在尝试编写一个函数来检查Shape*对象是否属于Circle.

它就是这样的

if Shape* object belongs to Object-Type Circle, then
cout << "It's a Circle, bruh!";
else
cout << "Ain't a circle, yo!";
Run Code Online (Sandbox Code Playgroud)

谷歌搜索后我开始:

void check(Shape & object){
    Circle& checkObject = dynamic_cast<Circle&>(object);

}
Run Code Online (Sandbox Code Playgroud)

main中的函数将通过以下方式调用:

check(*newRectangle);
check(*newCircle);
Run Code Online (Sandbox Code Playgroud)

但我还没有得到如何继续的线索:(.任何帮助和解释都表示赞赏.谢谢!

R S*_*ahu 6

  1. 尽量避免基于派生类型的逻辑.virtual尽可能使用成员函数.

    class Shape {
       public:
          virtual void print(std::ostream& out) const = 0;
       ...
    };
    
    Run Code Online (Sandbox Code Playgroud)

    并在派生的clases中实现该函数.

    class Circle : public Shape {
       public:
          virtual void print(std::ostream& out) const
          {
             out << "Got a Circle.\n";
          }
    
       ....
    };
    
    Run Code Online (Sandbox Code Playgroud)
  2. 如果使用virtual成员函数无法解决问题,则需要求助于dynamic_cast.

    Shape* shapePtr = <some pointer>;
    Circle* circlePtr = dynamic_cast<Circle*>(shapePtr);
    if ( circlePtr ) {
       // Access Circle functionality.
    }
    
    Run Code Online (Sandbox Code Playgroud)