首页 > 解决方案 > 为什么移动构造不从祖父母继承

问题描述

以下代码段无法编译,我不确定为什么:

#include <iostream>

class A {
    public:    
    A(int val) { std::cout << "A default is called" << std::endl;
                    m_val = val;};
    A(A && other) { std::cout << "A move constructor is called" << std::endl;
        m_val = other.m_val;
        other.m_val = 0;}
    int m_val;
};

class B : public A {
    public:
    using A::A;
    B() : A(5) { std::cout << "B default is called" << std::endl; };
};

class C : public B {
    public:
    using B::B;
    C() { std::cout << "C default is called" << std::endl; };
};

A createA(int val) { return A(val); }
C createC() { return C(); }

int main()
{
    C objC(createA(10));
    return 0;
}

我希望 C 从 B 继承移动构造函数,它从 A 继承。但我收到以下错误:

adam$ clang++ -std=c++17 test.cpp -o test
test.cpp:30:7: error: no matching constructor for initialization of 'C'
    C objC(createA(10));
      ^    ~~~~~~~~~~~
test.cpp:5:5: note: candidate inherited constructor not viable: no known conversion from 'A' to 'int' for 1st argument
    A(int val) { std::cout << "A default is called" << std::endl;
    ^
test.cpp:21:14: note: constructor from base class 'B' inherited here
    using B::B;
             ^
test.cpp:19:7: note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'A' to 'const C' for 1st argument
class C : public B {
      ^
test.cpp:19:7: note: candidate constructor (the implicit move constructor) not viable: no known conversion from 'A' to 'C' for 1st argument
class C : public B {
      ^
test.cpp:22:5: note: candidate constructor not viable: requires 0 arguments, but 1 was provided
    C() { std::cout << "C default is called" << std::endl; };
    ^
1 error generated.

为什么移动构造函数不是从 A 一直继承到 C?

标签: c++inheritance

解决方案


推荐阅读