如何在 gtest 中使用带有命名空间的友元类

use*_*089 2 c++ namespaces friend googletest

假设我的 Add.h 位于命名空间内,并且我将其设为 AddTest 的友元,以便它可以访问 AddTwoNumber。

namespace mynamespace
{

class Add
{
 friend class AddTest;

 public:
  Add(){};
  ~Add(){};

 private:
  int AddTwoNumber(const int a, const int b){return a+b};
};

}
Run Code Online (Sandbox Code Playgroud)

我的 AddTest.h 是

#include "Add.h"
#include "gtest/gtest.h"

class AddTest : public ::testing::Test
{
 protected:
  AddTest(){};
  virtual ~AddTest(){};

  virtual void SetUp()
  {
    mynamespace::Add addobj;
    result = addobj.AddTwoNumber(2, 3);
  };

  virtual void TearDown(){};

  int result;
};
Run Code Online (Sandbox Code Playgroud)

但是,它返回错误,因为 AddTwoNumber 是私有的。如果我在 Add.h 中取出“mynamespace”,该代码就可以工作。有没有办法保留命名空间但仍允许 AddTest 访问 Add.h 中的私有方法?

Cap*_*ffe 5

使用以下命令将 AddTest 限定在全局命名空间中

friend class ::AddTest;
Run Code Online (Sandbox Code Playgroud)

没有::它就会声明nynamespace::AddTest为朋友。