C++类型转换的问题
来源:百度知道 编辑:UC知道 时间:2024/05/09 20:46:24
我不明白下面的代码在用dynamic_cast做类型转换的时候为什么会报错
书上的代码也是这样的啊,麻烦给解释下谢谢!
以下是代码:
#include <typeinfo>
#include <iostream>
class Shape
{
public:
virtual void foo(){}
};
class Circle:public Shape{};
class Rectangles:public Shape{};
void Process(Shape *sp)
{
Circle* cp=dynamic_cast<Circle*>(sp);
if(cp!=0)
{
std::cout<<"Process a Circle"<<std::endl;
return;
}
Rectangles *rp=dynamic_cast<Rectangles*>(sp);
if(rp!=0)
{
std::cout<<"Process a Rectangle"<<std::endl;
return;
}
std::cout<<"Unknown Shape,cannot process"<<std::endl;
}
int main()
{
Circle circle;
Process(&circle);
Rectangles rect;
Process(&rect);
Shape shape;
Process(&shape);
return 0;
}
书上的代码也是这样的啊,麻烦给解释下谢谢!
以下是代码:
#include <typeinfo>
#include <iostream>
class Shape
{
public:
virtual void foo(){}
};
class Circle:public Shape{};
class Rectangles:public Shape{};
void Process(Shape *sp)
{
Circle* cp=dynamic_cast<Circle*>(sp);
if(cp!=0)
{
std::cout<<"Process a Circle"<<std::endl;
return;
}
Rectangles *rp=dynamic_cast<Rectangles*>(sp);
if(rp!=0)
{
std::cout<<"Process a Rectangle"<<std::endl;
return;
}
std::cout<<"Unknown Shape,cannot process"<<std::endl;
}
int main()
{
Circle circle;
Process(&circle);
Rectangles rect;
Process(&rect);
Shape shape;
Process(&shape);
return 0;
}
#include <typeinfo>
#include <iostream>
#include <exception>
class Shape
{
public:
virtual void foo(){}
//virtual ~Shape(){};
};
class Circle:public Shape{};
class Rectangles:public Shape{};
void Process(Shape *sp)
{
Circle* cp=dynamic_cast<Circle*>(sp);
if(cp!=0)
{
std::cout<<"Process a Circle"<<std::endl;
return;
}
Rectangles *rp=dynamic_cast<Rectangles*>(sp);
if(rp!=0)
{
std::cout<<"Process a Rectangle"<<std::endl;
return;
}
std::cout<<"Unknown Shape,cannot process"<<std::endl;
}
int main()
{
try{
Circle circle;
Process(&circle);
Rectangles rect;
Process(&rect);
Shape shape;
Process(&shape);
return 0;
}catch(exception& e)
{
std::cerr <<