小编scs*_*rin的帖子

如何通过共享 ptr 到共享 ptr 访问类的成员函数?

我有两个类,fooand bar,其中bar包含指向 的指针foo,如下所示。

#include<iostream>
#include<memory>
class foo {
private:
  int num{4};
public:
  void sum(const int& to_add) {num += to_add;}
  int access_num() {return num;}
};
class bar {
private:
  std::shared_ptr<foo> ptr;
public:
  void change_ptr(foo& f) {
    auto new_ptr = std::make_shared<foo>(f);
    ptr = std::move(new_ptr);
  }
  std::shared_ptr<foo> access_ptr() { return ptr; }
};
Run Code Online (Sandbox Code Playgroud)

如果我想通过 in 中的指针执行 的成员函数sum(),我该怎么做?目前,正在尝试foobar

  foo f;
  std::shared_ptr<bar> bar_ptr = std::make_shared<bar>();
  bar_ptr->change_ptr(f);
  // Add three to the int stored in …
Run Code Online (Sandbox Code Playgroud)

c++ pointers shared-ptr

3
推荐指数
1
解决办法
253
查看次数

标签 统计

c++ ×1

pointers ×1

shared-ptr ×1