我已在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*
答案 0 :(得分:2)
typeid()
仅在传递多态类型的左值时才实际执行RTTI查找。 Shape
是一种多态类型,但您没有传递Shape
左值,而是传递Shape*
。因此,当您将c
,s
和r
传递给typeid()
时,它会报告这些表达式的静态类型,即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;