假设我有:
- 两个类:P 和 C。
- P<>-C之间的组合关系,即P的每个实例都包含一个C的实例,当父P实例被销毁时,C的实例也被销毁。
要在 C++ I 中实现它:
- 定义两个类P和C;
- 定义一个类型为boost::shared_ptr的P的成员变量,并在P的构造函数中用一个新创建的对象对其进行初始化。
下面给出了一个代码示例。
#include "boost/scoped_ptr.hpp"
class C
{
public:
C() {}
private:
};
class P
{
public:
P() : childC(new C()) {}
private:
boost::shared_ptr<C> childC;
};
int main(int argc, char** argv)
{
P p;
}
不知何故,我无法构建这个简单的代码示例,而且我不明白为什么(我是编程新手)。
错误:
class ‘P’ does not have any field named ‘childC’
expected ‘;’ before ‘<’ token
invalid use of ‘::’
ISO C++ forbids declaration of ‘shared_ptr’ with no type
最佳答案
导致错误的最可能原因是您包含了 boost/scoped_ptr.hpp
你正试图声明一个 boost::shared_ptr
.您不太可能需要 boost::shared_ptr
在这里。
最简单的表达方式composition在这种情况下是
class C {};
class P
{
private:
C c_;
};
现在您可能希望通过使用只需要前向声明 C
的习惯用法来减少编译时依赖性, 在这种情况下 P
的标题可以是
#include <boost/scoped_ptr.hpp>
class C; // forward declaration
class P
{
public:
P() : c_(new C()) {}
private:
boost::scoped_ptr<C> c_;
};
关于c++ - boost::shared_ptr - 两个类之间的组合关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15014273/