以下代码段无法编译,我不确定原因:
#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的move构造函数,而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?