【问题标题】:Modifying an inherited member variable does not affect base class修改继承的成员变量不影响基类
【发布时间】:2019-07-24 05:10:28
【问题描述】:

我有以下两个类:

class A
{
public:

    A() : value(false) {}

    bool get() const
    {
        return value;
    }

protected:
    bool value;
};

class B : public A
{
public:

    void set()
    {
        value = true;
    }
};

现在我使用它们如下:

B* b = new B;
std::shared_ptr<A> a(b);

auto func = std::bind(&B::set, *b);

std::cout << a->get() << std::endl;
func();
std::cout << a->get() << std::endl;

我希望a-&gt;get() 在第二次调用时返回true,但func() 没有修改它的值。这是为什么呢?

【问题讨论】:

    标签: c++ class c++11 stdbind


    【解决方案1】:

    std::bind 按值获取其参数,因此您正在对*b 的副本进行操作。

    您需要通过std::ref传递原始对象:

    auto func = std::bind(&B::set, std::ref(*b));
    

    Live demo

    或者更简单的形式只是将指针传递给bind

    auto func = std::bind(&B::set, b);
    

    【讨论】:

      猜你喜欢
      • 2012-05-16
      • 2016-12-03
      • 1970-01-01
      • 1970-01-01
      • 2012-11-04
      • 2021-09-15
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      相关资源
      最近更新 更多