从基类调用重写函数?
我的问题可能最好通过一个例子来解释。
例如,我有2个类:一个基类和一个派生类:
class baseClass
{
public:
baseClass()
{
foo();
}
virtual bool foo() { printf("baseClass"); return false;}
};
class derivedClass : public baseClass
{
public:
bool foo()
{
printf("derivedClass");
return true;
}
};
当我创建categories
的实例时,baseClass
中的构造函数将被调用,并且foo()
将从它的构造函数中调用。问题是,baseClass 的构造函数正在调用自己的 foo()
,并且没有派生类已重写的重写的 foo()
。无论如何,有没有办法让基类调用重写的函数,而不是它自己的函数定义?
My question will probably be best explained by an example.
For example, I have 2 classes: A base class and a derived class:
class baseClass
{
public:
baseClass()
{
foo();
}
virtual bool foo() { printf("baseClass"); return false;}
};
class derivedClass : public baseClass
{
public:
bool foo()
{
printf("derivedClass");
return true;
}
};
When I create an instance of derivedClass
, the constructor in baseClass
will be called, and foo()
will be called from it's constructor. The problem is, the baseClass' constructor is calling its own foo()
and no the overridden foo()
that the derived class has overridden. Is there anyway to make the baseClass call the overridden function, not it's own definition of the function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不应该从构造函数调用虚拟方法,因为该对象尚未完全构造。本质上,派生类还不存在,因此无法调用其方法。
You should not call a virtual method from a constructor because the object has not yet been fully constructed. Essentially, the derived class doesn't exist yet, so its methods cannot be called.
在大多数语言中,这种行为要么是被禁止的,要么是未定义的,这是有充分理由的。
考虑一下:基类构造函数在子类构造函数之前运行,因此子类定义的任何变量都将未初始化。您确定要在这种情况下调用子类方法吗?
最简单的替代方法是在超类中定义一个initialize()方法,然后记住从子类构造函数中调用initialize()。
In most languages, this behavior is either prohibited or undefined, with good reason.
Consider this: the base class constructor is run before the subclass constructor, so any vars defined by the sublass will be uninitialized. Are you sure you want to call the subclassed method under those circumstances?
The simplest alternative is to define an initialize() method in your superclass, then just remember to call initialize() from your subclass constructor.