error: 'member' is private within this context - namespace
error: 'member' is private within this context - namespace
我在如下命名空间中有一个 class。
test.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);
};
test.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
的名称 space 中定义运算符 <<
:
namespace n1
{
std::ostream& operator << (std::ostream & str, const myClass& cls)
{
str << cls.a << " " << cls.b << std::endl;
}
}
因为你答应了myClass
有一个朋友名字-space n1
但你实际上在全局名字-space.[=15中声明了运算符=]
我在如下命名空间中有一个 class。 test.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);
};
test.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
的名称 space 中定义运算符 <<
:
namespace n1
{
std::ostream& operator << (std::ostream & str, const myClass& cls)
{
str << cls.a << " " << cls.b << std::endl;
}
}
因为你答应了myClass
有一个朋友名字-space n1
但你实际上在全局名字-space.[=15中声明了运算符=]