在C++中,是否可以从子类中排除基类中继承的类?
例如,如果你有三个这样的类:
class A
{
public:
int x;
};
class B : public A
{
public:
int y;
};
class C : public B
{
public:
int z;
};
类B
是否可能包含变量x
和y
,而类C
仅包含y
和z
?
我认为最接近您想要实现的是私有继承。
struct A
{
int x;
};
struct B : private A
{
int y;
};
struct C : B
{
int z;
};
int main()
{
C c;
c.x = 5; // error. you're not allowed to access members from A
c.y = 3; // ok
c.z = 4; // ok
}
所以A的数据仍然存在,但你无法从B之外访问它。
如果你想让数据在C中根本不存在,那么答案是否定的。继承就是在结构的开头有你父母的内容。
struct A
{
int x;
};
struct B : A
{
int y;
};
在内存中,B的一个实例将如下所示:
struct B
{
int x;
int y;
}
是的,可以满足您的变量继承约束。使用朋友类。通过在类声明中使用关键字friend
公开的友谊语义,可以使派生类能够访问其父类的私有成员。该链接包含友谊语义的完整教程。
你的代码看起来像:
class A
{
private:
int x;
friend class B;
};
class B : public A
{
public:
int y;
};
class C : public B
{
public:
int z;
};
由此,class B
可以访问class A
的private x
,但只能从class B
的定义内部访问。满足变量继承约束,class B
包含(并且可以使用(x
和y
,而class C
包含y
和z
。
另一种方式可以是私人继承,比如:
class A
{
private:
int x;
};
class B : private A
{
public:
int y;
};
class C : public B
{
public:
int z;
};
但这比friend
方法要严格得多。选择适合您需要的。