gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:54:36 26 4
gpt4 key购买 nike

我在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com