从派生类访问基类对象
Access base class object from derived class
我可能理解继承有误,但说if:
我有一个基类叫base,还有一个派生类叫derived,
在派生类的函数中,我可以访问派生类的Base对象吗?我想有点像这个,但对象类型是Base?
EDIT:我正在重写Derived类中的一个函数Base::foo(),但在这个重写的函数Derived::foo()中,我想用Base对象调用原始函数。
派生::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;
}
Derived*
可以隐式转换为Base*
,因此您可以执行以下操作:
const Base *base = this;
尽管您通常不需要这个,因为Base
的任何成员都是由Derived
继承的。
但如果foo()
是虚拟的,那么这样做:
const Base *base = this;
base->foo();
或等效地:
static_cast<const Base*>(this)->foo();
将不调用CCD_ 6而是调用Derived::foo()
。这就是虚拟函数的作用。如果你想调用一个特定版本的虚拟函数,你只需指定哪一个:
this->Base::foo(); // non-virtual call to a virtual function
当然,this->
部分并不是真正必要的:
Base::foo();
会很好地工作,但有些人更喜欢添加this->
,因为后者看起来像是对静态函数的调用(我对此没有偏好)。
要调用要覆盖的基类函数,请调用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;
}
};
相关文章:
- 按基类对象访问派生类资源时出错
- C++ 构造函数传递对基类对象的引用
- 使用基类对象访问派生的仅类方法
- 如何删除派生类中基类对象的新对象
- 使用基类对象调用Dervied Class函数
- 基类对象是否隐式添加到派生类中?
- 如果我有指向基类对象的指针,如何获取虚拟方法的地址?
- 如何不删除基类对象的副本?
- 如何根据基类对象中的变量值分配派生类中的变量?
- 从基类对象的向量中获取特定派生类的对象
- 您可以将派生的类对象作为函数参数代替基类对象吗?
- 如何使用基类对象设置派生类变量的值
- 通过引用派生类对象从基类对象执行向下转换时引发bad_cast异常
- 如何从现有基类对象创建派生类对象
- 子类对象列表重新解释为基类对象列表?(C++11).
- 派生的类指针使用static_cast指向基类对象
- 对我的基类对象数组使用大量的静态类型转换——这可以吗
- 我怎么知道基类对象的指针数组中元素的类型,它将为派生类分配内存
- 在C++中,为什么编译器不了解基类对象在编译时指向哪个对象?
- 为什么可以从实例化基类对象的投射指针调用非静态派生类方法