该程序运行无任何异常。你能解释一下为什么动态转换和静态转换都成功了吗?以及 C++ 如何设法解决所需的虚函数?
class Shape
{
private :
string helperFunction();
public :
virtual void draw() = 0;
virtual void type();
};
void Shape::type()
{
cout << "Shape Type";
}
// ----------------------------------------------------------------------------
class Circle : public Shape
{
private:
string circlething;
public :
virtual void draw();
virtual void type();
void CircleFunction();
};
void Circle::draw()
{
cout <<"Circle Draw" << endl;
}
void Circle::type()
{
cout <<"Circle Type" << endl;
}
void Circle::CircleFunction()
{
circlething = "Circle Thing";
cout << circlething;
cout << "Circle Function" << endl;
}
class Square : public Shape
{
private :
string squarething;
public :
virtual void draw();
virtual void type();
void SquareFunction();
};
void Square::draw()
{
cout <<"Square Draw" << endl;
}
void Square::type()
{
cout <<"Square Type" << endl;
}
void Square::SquareFunction()
{
squarething = "Square Thing";
cout << squarething;
cout << "Square Function" << endl;
}
// ----------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
vector<Shape *> shapes;
Circle circle;
Square square;
shapes.push_back(&circle);
shapes.push_back(&square);
vector<Shape *>::const_iterator i;
for (i = shapes.begin(); i < shapes.end(); ++i)
{
cout << "\n*** Simple Type ***\n" << endl;
(*i)->type();
(*i)->draw();
cout << "---Static Cast Circle--" << endl;
Circle* circle = static_cast<Circle*>(*i);
circle->type();
circle->draw();
circle->CircleFunction();
cout << "---Static Cast Square--" << endl;
Square* square = static_cast<Square*>(*i);
square->type();
square->draw();
square->SquareFunction();
cout << "---Static Cast Circle to Shape --" << endl;
Shape* shape1 = static_cast<Shape*> (circle);
shape1->type();
shape1->draw();
cout << "--- Dynamic Cast Circle to Shape --" << endl;
Shape* shape2 = dynamic_cast<Shape*> (circle);
shape2->type();
shape2->draw();
cout << "--- Static Cast Square to Shape --" << endl;
Shape* shape3 = static_cast<Shape*> (square);
shape3->type();
shape3->draw();
cout << "--- Dynamic Cast Square to Shape --" << endl;
Shape* shape4 = dynamic_cast<Shape*> (square);
shape4->type();
shape4->draw();
}
int x;
cin >> x;
return 0;
}