我可能对继承的理解有误,但如果:
我有一个名为 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/