【发布时间】:2020-09-04 08:28:09
【问题描述】:
我有这个简单的代码:
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
^
当C1 类的默认构造函数显式调用C0 构造函数传递参数时,为什么编译器会抱怨C0 中缺少默认构造函数?
当我在C0 中定义默认构造函数时,不会发生从C1 对C0(i) 的调用。所以成员变量C0::i_ 没有被初始化。当C2 被实例化时,不应该调用C0(i) 而不是C0 的默认构造函数吗?
【问题讨论】:
-
这是因为虚拟继承。在您最喜欢的 C++ 书籍中阅读有关虚拟继承的更多信息。 (clang 告诉你你需要做什么,但不告诉你为什么。)
标签: c++ inheritance default-constructor