从派生类访问基类对象

Access base class object from derived class

本文关键字:基类 对象 访问 派生      更新时间:2023-10-16

我可能理解继承有误,但说if:

我有一个基类叫base,还有一个派生类叫derived,

在派生类的函数中,我可以访问派生类的Base对象吗?我想有点像这个,但对象类型是Base?

EDIT:我正在重写Derived类中的一个函数Base::foo(),但在这个重写的函数Derived::foo()中,我想用Base对象调用原始函数。

派生::foo()const{

double Derived::foo() const {
  // s is a variable only associated with Derived
  double x;
  x = s + Base.foo(); // this is the line i dont know what im doing?!
  return x;
}

Derived*可以隐式转换为Base*,因此您可以执行以下操作:

const Base *base = this;

尽管您通常不需要这个,因为Base的任何成员都是由Derived继承的。

但如果foo()是虚拟的,那么这样做:

const Base *base = this;
base->foo();

或等效地:

static_cast<const Base*>(this)->foo();

将不调用CCD_ 6而是调用Derived::foo()。这就是虚拟函数的作用。如果你想调用一个特定版本的虚拟函数,你只需指定哪一个:

this->Base::foo(); // non-virtual call to a virtual function

当然,this->部分并不是真正必要的:

Base::foo();

会很好地工作,但有些人更喜欢添加this->,因为后者看起来像是对静态函数的调用(我对此没有偏好)。

要调用要覆盖的基类函数,请调用Base::Fun(...)

您执行以下Base::foo(),这里是完整的代码示例:

class Base
{
public:
    virtual double  foo() const
    {
        return 5;
    };
};
class Derived : Base
{
    int s;
public:
    Derived() : s(5)
    {
    }
    virtual double  foo() const
    {
        // s is a variable only associated with Derived
        double x;
        //NOTE THE Base::foo() call
        x = s + Base::foo(); // this is the line i dont know what im doing?!
        return x;
    }
};