在此示例中,我创建基础对象sphere(2),并将其地址分配给具有类型转换的派生类指针。然后我可以调用基础对象sphere(2)中不存在的fun()函数。我认为这很奇怪,因为Sphere中根本没有fun()的定义。但我可以进行类型转换并调用它。有人可以解释吗? 在此先感谢。从基类中不存在的基类中调用派生的方法
PS:输出是 “哈哈,我半径2球”
//---------sphere.h--------------
#ifndef SPHERE_H
#define SPHERE_H
class Sphere{
private:
double _radius;
public:
Sphere(double radius){
_radius = radius;
}
double getRadius(){
return _radius;
}
};
#endif
//-----------ball.h--------------
#ifndef BALL_H
#define BALL_H
#include <iostream>
#include "Sphere.h"
using namespace std;
class Ball : public Sphere
{
private:
string _ballName;
public:
Ball(double radius, string ballName): Sphere(radius){
_ballName = ballName;
}
string getName(){
return _ballName;
}
void fun(){
cout << "Haha I am a ball with radius " << getRadius() << endl;
}
void displayInfo(){
cout << "Name of ball: " << getName()
<< " radius of ball: " << getRadius() << endl;
}
};
#endif
//-------main.cpp----------------
#include "Ball.h"
#include "Sphere.h"
int main(){
Ball *ballPtr;
Sphere sphere(2);
ballPtr = (Ball *)&sphere;
ballPtr -> fun();
return 0;
}
是不是未定义的行为很好? – user657267
您可以使用C++ cast而不是c-cast。这里'dynamic_cast','ballPtr'将是'nullptr'。 – Jarod42
@ Jarod42这里使用'dynamic_cast'会导致编译时错误,因为'Sphere'不是多态的。 – user657267