c++ - boost::shared_ptr - 两个类之间的组合关系

标签 c++ boost shared-ptr

假设我有:

  • 两个类: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/

相关文章:

c++ - boost::dynamic_pointer_cast 在有效转换时返回 null

c++ - getter 可以标记为 `noexcept` 吗?

c++ - while循环中的QSerialPort?

c++ - C++二维数组的访问效率

boost - 在 Boost MPI 中使用骨架/内容机制发送复杂数据

boost - 通过 boost 消息队列发送复杂的数据结构

c++ - 如何在阻塞调用周围实现定时等待?

c++ - 串行编程(硬件握手)

c++ - 对象 std::shared_ptr 是否可以通过它的 std::weak_ptr 找到?

c++ - 将 std::move 与 std::shared_ptr 一起使用