我有这个简单的代码:
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
^
当类C0
的默认构造函数显式调用传递参数的C1
构造函数时,为什么编译器会抱怨类C0
中缺少默认构造函数?
当我在C0
中定义默认构造函数时,不会发生从C0(i)
到C1
的调用。因此成员变量C0::i_
未初始化。实例化C0(i)
时,是否应该调用C0
而不是默认的C2
构造函数?
最派生的类是负责构建虚拟基础的类。要解决此问题,请将: C0(k)
添加到C2
。