class Super { public: Super(); virtual void someMether(); protected: int mPritectedInt; private: int mPrivateInt; }; class Sub : public Super { public: Sub(); void someMether() override; //重写父类的someMether方法 void someOtherMether(); private: double mPrivateDouble; };
当这样声明时:
Sub mySub;
Super super = mySub;
super.someMether(); //这个调用的是Super类内的someMether();
可以这样理解:Super是一个小盒子,Sub时一个大盒子,因为Sub继承了Super,所以在Sub里边就会有独属于自己的方法,比Super的范围大(为了方便理解,其实这么说是错误的),所以当Super super = mySub;时,就相当于将一个大盒子变成一个小盒子,导致派生类数据和重写丢失,这种现象称为截断(slicing)
Super *p = new Sub;
p->someMether();
Sub mySub;
Super &super = mySub;
super.someMether();
结果就是p和super都是调用的Sub里的重写函数someMether();
顺便说一下禁止继承和重写的语法:
1.禁止继承
class Super final
{
public:
Super();
virtual void someMether();
protected:
int mPritectedInt;
private:
int mPrivateInt;
};
这就意味着Super是禁止其他类继承的。
比如是:
class Sub : public Super
{
public:
Sub()
void someOtherMether();
private:
double mPrivateDouble;
};
编译器会报错
2禁止重写
class Super
{
public:
Super();
virtual void someMether() final;
protected:
int mPritectedInt;
private:
int mPrivateInt;
};
class Sub : public Super
{
public:
Sub();
void someMether() override; //重写父类的someMether方法
void someOtherMether();
private:
double mPrivateDouble;
};
加入final后重谢父类Super的void someMether() 程序会报错。