当友元函数包含在命名空间中时,其定义需要加上命名空间前缀才能编译,示例代码如下:
测试.h:
#ifndef TEST_H
#define TEST_H
namespace TestNamespace
{
class TestClass
{
public:
void setValue(int &aI);
int value();
private:
int i;
friend void testFunc(TestClass &myObj);
};
void testFunc(TestClass &myObj);
}
#endif
测试.cpp:
#include "test.h"
using namespace TestNamespace;
void TestClass::setValue(int &aI)
{
i=aI;
}
int TestClass::value()
{
return i;
}
void testFunc(TestClass &myObj)
{
int j = myObj.i;
}
编译以上代码报错:
1>c:\qtprojects\namesp\test.cpp(17) : error C2248: 'TestNamespace::TestClass::i' : cannot access private member declared in class 'TestNamespace::TestClass'
1> c:\qtprojects\namesp\test.h(11) : see declaration of 'TestNamespace::TestClass::i'
1> c:\qtprojects\namesp\test.h(6) : see declaration of 'TestNamespace::TestClass'
但是如果我使用
void TestNamespace::testFunc(TestClass &myObj)
{
int j = myObj.i;
}
它编译,为什么函数需要以 namespace TestNamespace::testFunc 作为前缀而不是类,类 TestClass 和函数 testFunc 都包含在 header 中的 namespace 中。
最佳答案
TestClass
正在 testFunc
方法中使用。由于您包含了命名空间“using namespace TestNamespace;
”,因此它工作正常。
对于定义实现的 testFunc
方法,您需要告诉编译器 testfunc 属于命名空间 TestNamespace:
你可以这样做:
在.cpp 中
namespace TestNamespace
{
void testFunc(TestClass &myObj)
{
int j = myObj.i;
}
}
或
void TestNamespace::testFunc(TestClass &myObj)
{
int j = myObj.i;
}
关于c++ - 命名空间内的友元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1749311/