【发布时间】:2021-01-26 16:07:42
【问题描述】:
有没有办法用 using 语句继承私有构造函数? 我尝试添加朋友声明,但似乎不起作用。
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,因为如果我显式创建委托构造函数,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);
}
【问题讨论】:
-
也许只是措辞,但是当你继承时,一切都被继承了,还有私有成员,只是访问它们的问题
-
@idclev463035818 是的,你当然是对的。应该是“可以从继承者之外的范围继承和使用”.. 呃....你明白为什么我没有:)
-
如何访问私有基类构造函数?您可以跳过“是否可以继承”部分,因为所有成员都是继承的。虽然,没关系,这个问题已经很清楚了,可以回答,但我不想让你变得更糟
标签: c++ c++11 constructor using