[英]Composition between abstract classes
Is it possible to build a relationship of composition (not aggregation) between two abstract classes? 是否可以在两个抽象类之间建立组成关系(而非聚合)?
I don't think so because I cannot instantiate an abstract class. 我不这样认为,因为我无法实例化一个抽象类。 But maybe there's a simple way to do it.
但是也许有一种简单的方法可以做到这一点。
Yes: 是:
class A
{
virtual ~A() = 0;
};
class B
{
virtual ~B() = 0;
A* mA;
};
You are allowed to have pointers to abstract types. 您可以使用指向抽象类型的指针。
You can use a pointer or reference to the other class. 您可以使用指针或对其他类的引用。 For example:
例如:
class A {
public:
virtual void m() = 0;
virtual ~A() { }
};
class B {
public:
virtual void m() = 0;
virtual ~A() { }
private:
boost::scoped_ptr<A> a;
};
In C++11 you can use std::unique_ptr
instead. 在C ++ 11中,您可以改用
std::unique_ptr
。 Note that this makes B
noncopyable—that is somewhat common for classes using subtype polymorphism. 请注意,这使
B
不可复制-这对于使用子类型多态性的类来说有点常见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.