【问题标题】:How are constructors with default parameters called in inheritance hierarchy? [duplicate]在继承层次结构中如何调用具有默认参数的构造函数? [复制]
【发布时间】: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 中定义默认构造函数时,不会发生从C1C0(i) 的调用。所以成员变量C0::i_ 没有被初始化。当C2 被实例化时,不应该调用C0(i) 而不是C0 的默认构造函数吗?

【问题讨论】:

  • 这是因为虚拟继承。在您最喜欢的 C++ 书籍中阅读有关虚拟继承的更多信息。 (clang 告诉你你需要做什么,但不告诉你为什么。)

标签: c++ inheritance default-constructor


【解决方案1】:

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

【讨论】:

  • 请不要回答明显的欺骗。它使网站更难维护。
猜你喜欢
  • 1970-01-01
  • 2016-03-24
  • 2015-06-16
  • 1970-01-01
  • 1970-01-01
  • 2012-11-03
  • 2017-10-04
  • 1970-01-01
  • 2011-05-20
相关资源
最近更新 更多