gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:32:58 25 4
gpt4 key购买 nike

我在命名空间中有一个类,如下所示。测试.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在 namespace 中有一个 friend n1但实际上您在全局 namespace 中声明了运算符。

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com