C ++基本构造函数调用将在派生构造函数中构造的参数 [英] C++ Base constructor calling with parameter that will be constructed in the derived constructor

查看:156
本文介绍了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.

这篇关于C ++基本构造函数调用将在派生构造函数中构造的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆