从基类调用基类中不存在的派生方法
Call derived method which does not exist in base class from base class
在本例中,我创建了基本对象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;
}
那只是运气。您正在调用对象上的函数,同时假定它是另一种类型(Ball
是Sphere
,但并非所有Sphere
都是Balls
,而且那个当然不是)。这是未定义行为,可以做任何事情,包括向你的猫敬酒。小心。
该函数不是虚函数,所以它只通过对象指针的类型调用,您强制为Ball *
。"球"类直接和非虚拟地从"球体"继承,没有额外的基类,所以-你很幸运!- Sphere::radius
成员相对于球的*this
的位置在getRadius()
中是正确的,你得到一个正确的输出
相关文章:
- 指向基类派生类的 std::unique_ptr 的指针
- 从多个模板化基类派生时出现"隐藏重载的虚函数"警告
- 从模板基类派生是否在派生类声明的点实例化模板
- 使从一个基类派生的类能够使用继承的受保护成员
- C++多态性访问基类派生类字段
- C++派生类的设置属性到从同一基类派生的未知类对象
- 使用void* 参数定义纯虚函数的抽象基类.派生类匹配参数是指向某种类型的指针
- 在C++中,如何使用将保存从基类派生的任何对象的类成员
- 如何测试从依赖于外部系统的外部基类派生的类
- 如何从模板基类派生非模板类
- 在派生类中使用声明并不能隐藏从基类派生的相同函数
- 从具有静态结构的基类派生
- 具有从 c++ 中的非模板基类派生的模板类的事件系统
- C++ 调用从基类派生的覆盖函数
- 不清楚如何在从抽象基类派生的类中实现运算符重载
- 如何正向声明从正向声明的模板基类派生的类
- 是否可以从 std::enable_shared_from_this 和抽象基类派生
- 多态性c++,试图访问从抽象基类派生的类的成员函数
- C++多重继承,基类派生自同一类
- 基类派生类访问-如何