c++ - 从派生类访问基类对象

标签 c++ inheritance

我可能对继承的理解有误,但如果:

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

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

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

派生::foo() 常量{

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();

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

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

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

Base::foo();

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

关于c++ - 从派生类访问基类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29156783/

相关文章:

c++ - C 中的结构封装

java - 为什么调用父类方法?

java - 如何从继承类调用的抽象类调用抽象方法

java - 抽象类 : class, 接口(interface)或预期枚举错误

c++ - 不要在最后一个数字后打印空格

c++ - decltype 和隐藏外部名称的类成员名称之间的交互

C++ 和 Windows , CRT

javascript - 如何创建与其他对象类型相同的新对象

java - 接口(interface)扩展等同于继承吗? ( java )

c++ - 如何在 Tensorflow 的 C++ API 中解码后获取图像形状