c++ - 命名空间内的友元函数

标签 c++ namespaces

当友元函数包含在命名空间中时,其定义需要加上命名空间前缀才能编译,示例代码如下:

测试.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/

相关文章:

c++ - 在 gcc Linux 中将静态库链接到动态库

c++ - 自动 vector 边界检查而不会使我的程序崩溃

C++:从数组中设置多个变量

c++ - 函数定义为限定 id

c# - 命名空间不存在

c++ - 如何避免丢弃消息 zeromq pub sub

c++ - 如何创建在构造函数期间初始化的类成员对象

xml - Delphi - IXMLNode 中的命名空间 URI 无效

c++ - 如果参数与数据成员同名怎么办?

c# - 从插件访问 C# 中的第三方命名空间