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

问题描述

我有两个类,foobar,其中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; }
};

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

  foo f;
  std::shared_ptr<bar> bar_ptr = std::make_shared<bar>();
  bar_ptr->change_ptr(f);
  // Add three to the int stored in f via the pointer
  bar_ptr->access_ptr()->sum(3);
  std::cout << f.access_num() << std::endl;

不起作用,输出4。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)