从基类调用基类中不存在的派生方法

Call derived method which does not exist in base class from base class

本文关键字:基类 派生 方法 调用 不存在      更新时间:2023-10-16

在本例中,我创建了基本对象sphere(2),并通过类型转换将其地址分配给派生类指针。然后我可以调用基本对象球体(2)中不存在的fun()函数。我认为这很奇怪,因为Sphere中根本没有fun()的定义。但我可以进行类型转换并调用它。有人能解释一下吗?提前感谢。

PS:输出是"Haha I am a ball with radius 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;
}

那只是运气。您正在调用对象上的函数,同时假定它是另一种类型(BallSphere,但并非所有Sphere都是Balls,而且那个当然不是)。这是未定义行为,可以做任何事情,包括向你的猫敬酒。小心。

该函数不是虚函数,所以它只通过对象指针的类型调用,您强制为Ball *。"球"类直接和非虚拟地从"球体"继承,没有额外的基类,所以-你很幸运!- Sphere::radius成员相对于球的*this的位置在getRadius()中是正确的,你得到一个正确的输出