gpt4 book ai didi

c++ - 继承构造函数、默认构造函数和可见性

转载 作者:可可西里 更新时间:2023-11-01 17:40:02 25 4
gpt4 key购买 nike

[namespace.udecl]/18 所述:

[...] A using-declaration that names a constructor does not create a synonym; instead, the additional constructors are accessible if they would be accessible when used to construct an object of the corresponding base class, and the accessibility of the using-declaration is ignored. [...]

因此,以下代码无法编译:

class B { protected: B(int) { } };
class D: B { using B::B; };
int main () { D d{0}; }

它返回一个与所有主要编译器大致相同的错误:

declared protected here

另一方面,编译以下代码:

class B { protected: B() { } };
class D: B { using B::B; };
int main () { D d{}; }

它不应该因为与前面示例中导致错误的相同原因而编译失败吗?
它允许编译什么?

最佳答案

class B { protected: B() { } };
class D: B { using B::B; };
int main () { D d{}; }

D 在这种情况下没有用户定义的构造函数,因此编译器会为您生成一个(公共(public)的)调用 B::B(但不是因为using,在这种情况下没有任何效果),然后由 main 调用编译器生成的构造函数。

class B { protected: B(int) { } };
class D: B { using B::B; };
int main () { D d{0}; }

即使 D 在这里没有用户定义的构造函数,编译器生成的构造函数也被隐式删除,因为 B 只有一个构造函数接受 intD 也有一个接受 int 的构造函数(using 就是这样做的)但是这个构造函数被标记为 protected 并且因此 main 无法访问。

关于c++ - 继承构造函数、默认构造函数和可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40081920/

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