从派生类访问基类对象
我可能理解遗传错误,但如果:
我有一个名为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;
}
回答(2)
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->
,因为后者看起来像是对静态函数的调用(我对这个问题没有偏好) .
2 years ago
要调用要覆盖的基类函数,请调用
Base::Fun(...)
.你执行以下
Base::foo()
,这是一个完整的代码示例: