如何使用gmock MOCK_METHOD进行重载对象引用?

问题描述 投票:0回答:1

我重载了对象引用以返回值,例如:

class MyClass : public MyClassInterface {
  public:
    virtual ~MyClass() override;
    operator const int&() const override {
        return m_value;
    }
  private:
    int m_value{};
};

获取值:

MyClass myclass;
int val = myclass;

现在我想模拟这个运算符方法,并发现如何对重载运算符使用gmock MOCK_METHOD?。我验证的例子如下:

class Foo {
  public:
virtual ~Foo() {}
virtual int operator[](int index) = 0;
};

class MockFoo : public Foo {
  public:
MOCK_METHOD(int, BracketOp, (int index));
virtual int operator[](int index) override { return BracketOp(index); }
};

编译没有错误。现在我尝试修改这个示例以满足我的需要:

class Bar {
  public:
virtual ~Bar() {}
virtual operator const int&() = 0;
};

class MockBar : public Bar {
  public:
MOCK_METHOD(int, RefOp, ());
virtual operator const int&() override { return RefOp(); }
};

但是现在我遇到编译错误:

error: returning reference to temporary [-Werror=return-local-addr]
 1173 |     virtual operator const int&() override { return RefOp(); }
      |                                                     ~~~~~^~

我做错了什么?如何使 Bar 类像 Foo 类一样编译?

c++ operator-overloading googlemock
1个回答
0
投票

您的原始代码:

MOCK_METHOD(const int&, value, (), (const));

查看更新后的代码

MOCK_METHOD(const int&, RefOp, ());
© www.soinside.com 2019 - 2024. All rights reserved.