具有默认参数的构造函数如何在继承层次结构中调用?

How are constructors with default parameters called in inheritance hierarchy?

我有这个简单的代码:

class C0
{
        public:
                C0(std::string i) : i_(i) {}

        private:
                std::string i_;
};

class C1 : public virtual C0
{
        public:
                constexpr static auto const e{"e"};

                C1(std::string i = e) : C0(i) {}
};

class C2 : public virtual C1
{
        public:
                C2(std::string k) : k_(k) {}

        private:
                std::string k_;
};

编译为:[clang++|g++] -std=c++17 example.cpp

我收到以下错误:

使用 g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0:

example.cpp: In constructor ‘C2::C2(std::__cxx11::string)’:
example.cpp:23:41: error: no matching function for call to ‘C0::C0()’
                 C2(std::string k) : k_(k) {}
                                         ^
example.cpp:6:17: note: candidate: C0::C0(std::__cxx11::string)
                 C0(std::string i) : i_(i) {}
                 ^~
example.cpp:6:17: note:   candidate expects 1 argument, 0 provided
example.cpp:3:7: note: candidate: C0::C0(const C0&)
 class C0
       ^~
example.cpp:3:7: note:   candidate expects 1 argument, 0 provided
example.cpp:3:7: note: candidate: C0::C0(C0&&)
example.cpp:3:7: note:   candidate expects 1 argument, 0 provided

使用 clang++ 版本 6.0.0-1ubuntu2:

example.cpp:23:17: error: constructor for 'C2' must explicitly initialize the base class 'C0' which does not have a default constructor
                C2(std::string k) : k_(k) {}
                ^
example.cpp:3:7: note: 'C0' declared here
class C0
      ^

当 class C1 的默认构造函数显式调用 C0 构造函数传递争论?

当我在 C0 中定义默认构造函数时,不会发生从 C1C0(i) 的调用。所以成员变量 C0::i_ 没有被初始化。实例化 C2 时,不应该调用 C0(i) 而不是 C0 的默认构造函数吗?

最派生的class是负责构建虚拟基地的。要解决此问题,请将 : C0(k) 添加到 C2