从派生 class 访问基础 class 对象
Access base class object from derived class
我可能对继承的理解有误,但如果:
我有一个名为 Base 的基 class 和一个名为 Derived 的派生 class,
在 Derived class 的函数中,我可以访问 Derived class 的 Base 对象吗?
我想有点像 *this 但对象类型是 Base ?
编辑:我在 Derived class 中覆盖了一个函数 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;
}
要调用您要覆盖的基本 class 函数,您可以调用 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;
}
};
A 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->
,因为后者看起来像是对静态函数的调用(我对此没有偏好)。
我可能对继承的理解有误,但如果:
我有一个名为 Base 的基 class 和一个名为 Derived 的派生 class,
在 Derived class 的函数中,我可以访问 Derived class 的 Base 对象吗? 我想有点像 *this 但对象类型是 Base ?
编辑:我在 Derived class 中覆盖了一个函数 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;
}
要调用您要覆盖的基本 class 函数,您可以调用 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;
}
};
A 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->
,因为后者看起来像是对静态函数的调用(我对此没有偏好)。