gpt4 book ai didi

c++ - 是否可以在 cpp >= 11 中使用继承私有(private)构造函数

转载 作者:行者123 更新时间:2023-12-03 06:56:01 25 4
gpt4 key购买 nike

有没有办法用 using 语句继承私有(private)构造函数?我尝试添加好友声明,但似乎没有用。

struct B;
struct A
{
private:
A(int x) {}
A(int y, double z) {}
friend struct B;
};
struct B : public A
{
public:
using A::A;
//B(int x) : A(x) {}
//B(int x, int y) : A(x, y) {}
};
void demo()
{
B b1(5); // does not compile - implicit constructor is not accessible
B b2(4, 9.0);
}

我想知道是否有任何方法可以通过 using 来实现,因为如果我显式创建委托(delegate)构造函数,friend 语句就可以工作,所以这个接缝不一致:

struct B;
struct A
{
private:
A(int x) {}
A(int y, double z) {}
friend struct B;
};
struct B : public A
{
public:
B(int x) : A(x) {} // OK
B(int x, int y) : A(x, y) {}
};

void demo()
{
B b1(5); // OK
B b2(4, 9.0);
}

最佳答案

继承构造函数的可访问性不受引入它们的 using 声明的可访问性的影响。

[namespace.udecl] (emphasis mine)

19 A synonym created by a using-declaration has the usualaccessibility for a member-declaration. A using-declarator that namesa constructor does not create a synonym; instead, the additionalconstructors are accessible if they would be accessible when used toconstruct an object of the corresponding base class, and theaccessibility of the using-declaration is ignored.

因为你不能在main中访问A的构造函数,所以在中构造一个B也是不可访问的main 任一个(您可以使用它在 B 的范围内构造 BA > 不过,出于友元)。您需要为类外访问明确说明某种转发器。由于您似乎在追求“包罗万象”,因此可以采用一个相当简单的解决方案

template<typename... Args>
B(Args&&... args) : A(std::forward<Args>(args)...) {}

关于c++ - 是否可以在 cpp >= 11 中使用继承私有(private)构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64316246/

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