从派生类访问基类对象

Dot*_*ash 2 c++ inheritance

我可能理解遗传错误,但如果:

我有一个名为Base的基类和一个名为Derived的派生类Base,

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

编辑:我在Derived类中重写了一个函数Base :: foo(),但在这个重写函数Derived :: foo()中我想用Base对象调用原始函数.

Derived :: 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;
}
Run Code Online (Sandbox Code Playgroud)

rod*_*igo 7

A Derived*可以隐式转换为Base*,所以你可以这样做:

const Base *base = this;
Run Code Online (Sandbox Code Playgroud)

虽然你通常不需要这个,因为任何成员Base都是继承的Derived.

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

const Base *base = this;
base->foo();
Run Code Online (Sandbox Code Playgroud)

或等效地:

static_cast<const Base*>(this)->foo();
Run Code Online (Sandbox Code Playgroud)

不会打电话Base::foo()但是Derived::foo().这就是虚函数的功能.如果要调用特定版本的虚拟函数,只需指定哪一个:

this->Base::foo(); // non-virtual call to a virtual function
Run Code Online (Sandbox Code Playgroud)

当然,这this->部分并不是必需的:

Base::foo();
Run Code Online (Sandbox Code Playgroud)

会工作得很好,但是有些人喜欢添加,this->因为后者看起来像是对静态函数的调用(我对这个问题没有偏好).


Gar*_*zer 4

要调用您要重写的基类函数,请调用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;
    }
};
Run Code Online (Sandbox Code Playgroud)