【发布时间】:2016-10-28 15:14:57
【问题描述】:
所以我有这个非常短的代码:
test.cpp
class Base {
public:
Base(int i) {};
};
class Child : public virtual Base {
using Base::Base;
};
int main(int argc, char * argv[]) {
auto *child = new Child(1);
return 0;
};
在clang++(3.8.0)下编译良好:
$ clang++ test.cpp -std=c++11
虽然在 g++ (5.4.0) 下失败:
$ g++ test.cpp -std=c++11
test.cpp: In function ‘int main(int, char**)’:
test.cpp:14:30: error: use of deleted function ‘Child::Child(int)’
auto *child = new Child(1);
^
test.cpp:8:17: note: ‘Child::Child(int)’ is implicitly deleted because the default definition would be ill-formed:
using Base::Base;
^
test.cpp:8:17: error: no matching function for call to ‘Base::Base()’
test.cpp:3:9: note: candidate: Base::Base(int)
Base(int i) {};
^
test.cpp:3:9: note: candidate expects 1 argument, 0 provided
test.cpp:1:7: note: candidate: constexpr Base::Base(const Base&)
class Base {
^
test.cpp:1:7: note: candidate expects 1 argument, 0 provided
test.cpp:1:7: note: candidate: constexpr Base::Base(Base&&)
test.cpp:1:7: note: candidate expects 1 argument, 0 provided
出于某种原因,g++ 期望 Base 类具有默认构造函数。这是为什么呢?
编辑:这也无法复制。这段代码:
auto child = Child(1);
在 g++ 下产生同样的错误,而这个:
Child child(1);
工作正常。但我还是不明白为什么?
编辑 2: 如果没有 virtual 关键字,它在两种编译器下都能正常工作。
【问题讨论】:
-
有趣。如果您删除 Child 的
virtual继承,或者如果您为 Child 显式定义构造函数:Child(int i) : Base(i) {},则会编译。