c++ - 错误: 'member' is private within this context - namespace

标签 c++ compiler-errors namespaces operator-overloading friend-function

我在命名空间中有一个类,如下所示。 测试.h

#include <iostream>
using std::cout;
namespace n1
{
    class myClass;
}

class n1::myClass
{
public:
    myClass(int na, int nb):a(na), b(nb){}
private:
    int a;
    int b;
friend std::ostream& operator << (std::ostream & stream, const n1::myClass& cls);
};

测试.cpp

#include "test.h"
std::ostream& operator << (std::ostream & str, const n1::myClass& cls)
{
    str << cls.a << " " << cls.b << std::endl;
}

在编译时,我收到以下错误。

test.h: In function ‘std::ostream& operator<<(std::ostream&, const n1::myClass&)’:
test.h:13:6: error: ‘int n1::myClass::a’ is private
test.cpp:5:13: error: within this context
test.h:14:6: error: ‘int n1::myClass::b’ is private
test.cpp:5:29: error: within this context

如何克服这些错误?

最佳答案

您可以定义运算符 <<myClass 命名空间内定义为:

namespace n1
{
 std::ostream& operator << (std::ostream & str, const myClass& cls)
 {
    str << cls.a << " " << cls.b << std::endl;
 }
}

因为你答应过myClass在命名空间 n1 有一个 friend 但实际上您在全局 namespace 中声明了该运算符。

关于c++ - 错误: 'member' is private within this context - namespace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43304914/

相关文章:

c++ - vss 初始化备份失败,返回码为 E_UNEXPECTED

c++ - 将具有二进制的 QString 转换为具有十六进制的 QString

python - 关于 C++ 和 python 的 tensorflow 的 Inception v3 指南

PHP:如何使用::而不是\访问命名空间类?

c++ - 在类定义中初始化数据成员

c++ - ns3中的构建错误,退出状态为1 :

python - pygame pygame.error : Error reading from ICO

compiler-errors - 有些人在gcc中定义了编译成功,但是g++失败了

c++ - 如何在 C++ 中访问语言环境和全局

c# - 合并 xml 命名空间