c++ - RTTI 行为未按预期出现

标签 c++ rtti

我在 MS Visual Studio Express 2012 中编写了这段代码以查看 rtti 行为。
但它没有按预期工作。
我的代码有什么问题?

Shape.h

class Shape
{
public:
    Shape(){}
    virtual ~Shape(){}
    virtual double area() = 0;
};

class Square : public Shape
{
    int a;
public:
    ~Square(){}
    Square(int );
    virtual double area();
};

class Rectangle : public Shape
{
    int l;
    int b;
public:
    ~Rectangle(){}
    Rectangle(int,int);
    virtual double area();
};

class Circle : public Shape
{
    int r;
public:
    ~Circle(){}
    Circle(int);
    virtual double area();
};

ShapeMain.cpp

int main()
{
    Shape* c = new Circle(4);
    cout<< "Area of circle:" << c->area() << endl;
    cout << typeid(c).name();

    Shape* s = new Square(4);
    cout<< "Area of square:" << s->area() << endl;
    cout << typeid(s).name();

    Shape* r = new Rectangle(4,5);
    cout<< "Area of rectangle:" << r->area() << endl;
    cout << typeid(r).name();

}

输出

Area of circle:50.24
class Shape *           //Expected class Circle*
Area of square:16
class Shape *           //Expected class Square*
Area of rectangle:20
class Shape *           //Expected class Rectangle*   

最佳答案

typeid()只有在传递多态类型的左值时才实际执行 RTTI 查找。 Shape是多态类型,但您没有传递 Shape左值,你正在传递一个 Shape* .所以当你经过 c , srtypeid() ,它报告这些表达式的静态类型,即 Shape* .

要获得运行时查找,您可以取消引用您的指针:std::cout << typeid(*r).name() << std::endl;

或者您可以直接保留引用:

Circle circle{4};
Shape& c = circle;
cout << "Area of circle:" << c.area() << endl;
cout << typeid(c).name() << endl;

关于c++ - RTTI 行为未按预期出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22285002/

相关文章:

c++ - 将 void* 映射回其原始类型

xml - 将 Delphi 对象树序列化为 XML 的好方法是什么——使用 RTTI 而不是自定义代码?

c++ - 奇怪的逗号运算符行为

c++ - mingw32-make ERROR,错误: 'once_flag' in namespace 'std' does not name a type

c++ - dynamic_cast 的性能

c++ - 没有 RTTI 的 ASIO

c++ - 如何使用复选框更改 QGraphicsView 背景

python - 使 C++ 模块成为 Python 包的一部分

c++ - 没有内联汇编的 x64 函数绕行

json - SuperObject 序列化私有(private)变量而不是属性