C ++基本构造函数调用将在派生构造函数中构造的参数
QUESTION 1)
class Base {
Base(std::string name);
virtual std::string generateName();
}
class Derived : Base {
Derived();
virtual std::string generateName();
}
这里有一个问题:
generateName()会调用什么方法?
what method will be called on generateName() ?
Derived :: Derived : Base(generateName()) {
//what method will be called on generateName() ?
}
问题2)
我应该怎么做呢?如果默认构造函数必须接受一个参数,但我需要在Derived构造函数中生成该参数?
how should i make it? if the default constructor must accept a parameter, but i need to generate that parameter in the Derived constructor?
对于行为, Derived :: generateName()
使用静态成员函数或非成员函数。将被调用。 C ++标准中定义此行为的长句说(C ++ 03 12.7 / 3):
As for the behavior, Derived::generateName()
will be called. The long sentence in the C++ Standard that defines this behavior says (C++03 12.7/3):
当调用虚函数时直接或间接从构造函数(包括从数据成员的mem初始化器)或从析构函数,并且调用应用的对象是正在构造或销毁的对象,调用的函数是在构造函数中定义的函数,
析构函数自己的类或其基础之一,但不是一个函数将其覆盖在从构造函数或析构函数的类派生的类中,或者覆盖最多派生对象的其他基类之一。
When a virtual function is called directly or indirectly from a constructor (including from the mem-initializer for a data member) or from a destructor, and the object to which the call applies is the object under construction or destruction, the function called is the one defined in the constructor or destructor's own class or in one of its bases, but not a function overriding it in a class derived from the constructor or destructor's class, or overriding it in one of the other base classes of the most derived object.
由于在虚拟调用时执行的构造函数是 Derived
构造函数, Derived :: generateName()
被调用。
Because the constructor being executed at the time of the virtual call is the Derived
constructor, Derived::generateName()
is called.
现在删除的答案正确地引用了Scott Meyers的一篇文章,推荐在施工或销毁过程中从不调用虚拟函数。调用overrider的规则很复杂,很难记住。
A now-deleted answer rightly referred to an article by Scott Meyers that recommends "Never Call Virtual Functions during Construction or Destruction." The rules for what overrider gets called are complex and difficult to remember.