gpt4 book ai didi

c++ - 为什么我不能继承虚拟基础的构造函数?

转载 作者:搜寻专家 更新时间:2023-10-31 00:34:38 24 4
gpt4 key购买 nike

我正在尝试使用 g++ 4.9.0 编译以下简单代码:

struct A {
explicit A(int x) { }
};

struct B : public virtual A {
using A::A;
};

int main(int argc, char** argv) {
B b(0);
return 0;
}

但是我得到以下错误:

$ g++ -std=c++11 main.cpp
main.cpp: In function ‘int main(int, char**)’:
main.cpp:10:10: error: use of deleted function ‘B::B(int)’
B b(0);
^
main.cpp:6:14: note: ‘B::B(int)’ is implicitly deleted because the default definition would be ill-formed:
using A::A;
^
main.cpp:6:14: error: no matching function for call to ‘A::A()’
main.cpp:6:14: note: candidates are:
main.cpp:2:14: note: A::A(int)
explicit A(int x) { }
^
main.cpp:2:14: note: candidate expects 1 argument, 0 provided
main.cpp:1:8: note: constexpr A::A(const A&)
struct A {
^
main.cpp:1:8: note: candidate expects 1 argument, 0 provided
main.cpp:1:8: note: constexpr A::A(A&&)
main.cpp:1:8: note: candidate expects 1 argument, 0 provided

我做错了什么吗?是编译器错误吗?

最佳答案

这是一个 GCC bug . §7.3.3 [namespace.udecl]/p3 要求

In a using-declaration used as a member-declaration, the nested-name-specifier shall name a base class of the class being defined. If such a using-declaration names a constructor, the nested-name-specifier shall name a direct base class of the class being defined...

AB 的直接基础, 所以 using A::A;是允许的。

标准规定(§12.9 [class.inhctor]/p8):

An implicitly-defined inheriting constructor performs the set of initializations of the class that would be performed by a user-written inline constructor for that class with a mem-initializer-list whose only mem-initializer has a mem-initializer-id that names the base class denoted in the nested-name-specifier of the using-declaration and an expression-list as specified below, and where the compound-statement in its function body is empty (12.6.2). If that user-written constructor would be ill-formed, the program is ill-formed. Each expression in the expression-list is of the form static_cast<T&&>(p), where p is the name of the corresponding constructor parameter and T is the declared type of p.

因此对应的用户编写的构造函数是

B::B(int x) : A(static_cast<int&&>(x)) { }

这是良构的。

关于c++ - 为什么我不能继承虚拟基础的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25653647/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com