Эта программа работает без каких-либо исключений. Не могли бы вы объяснить, почему успешные динамические статические и статические роли? И как 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;
}
Можете ли вы объяснить, почему статические роли также успешны? – unj2
@ kunj2aan: 'static_cast' даже не пытается выяснить, действительно ли выполнено преобразование. В вашем случае это, вероятно, работает в основном потому, что ваши функции-члены не используют никаких данных класса, поэтому обращение к ним с помощью указателя 'this', указывающего на неправильные данные, не вызывает видимых вреда/проблем. –
Привет. Я изменил код с новыми функциями-членами, и программа все еще работает без проблем. Это ты имел в виду? – unj2