[英]Composition of derived classes
I have a question regarding composition and inheritance in C++: 我对C ++中的组成和继承有疑问:
I have a base class 'A'
and a derived class 'B'
( 'B'
inherits members from 'A'
), is it possible use 'B'
as a member of 'A'
by composition? 我有一个基类
'A'
和一个派生类'B'
( 'B'
继承了'A'
成员),是否有可能将'B'
用作组成的'A'
的成员?
As to "A has B member, B derived from A": Practically, you cannot declare such a thing. 关于“ A有B成员,B源自A”:实际上,您不能声明这种东西。 If class A has a member of type B, then B needs to be declared before A. If B uses A as a base, A must be declared before B.
如果类A具有类型B的成员,则需要在A之前声明B。如果B使用A作为基数,则必须在B之前声明A。
As to composition, if you wanted to do such a thing, you could have to use indirection (pointer, smart-pointer, etc). 至于合成,如果您想做这样的事情,则可能必须使用间接寻址(指针,智能指针等)。
class B;
class A {
B *b;
};
class B : public A {
};
One might argue that (in C++) using pointers is not composition; 有人可能会争辩说(在C ++中)使用指针不是组合。 however, in Java, all Objects are "pointers", so composition is:
但是,在Java中,所有对象都是“指针”,因此组成为:
class A {
B b;
}
class B extends A {
}
However you may embed a B*
field. 但是,您可以嵌入
B*
字段。 Hence a const B&
should be possible too, and behave like a B
. 因此,
const B&
应该也是可能的,并且表现得像B
(Mind I am now a sandbox java programmer.) (请记住,我现在是一个沙盒Java程序员。)
class B;
class A {
B& b;
};
BTW you might not even embed an A in an A. 顺便说一句,您甚至可能没有在A中嵌入A。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.