【问题标题】:error: 'member' is private within this context - namespace错误:“成员”在此上下文中是私有的 - 命名空间
【发布时间】:2017-09-04 10:04:29
【问题描述】:

我在命名空间中有一个类,如下所示。 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

如何克服这些错误?

【问题讨论】:

  • 也许问题是流的名称,在cpp中你写了str和头文件流。你也试过把朋友放在cpp中吗?
  • @Serizba:不,您甚至可以删除名称 stream 并仅按类型保留定义。

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


【解决方案1】:

您可以在定义myClass 的命名空间内定义运算符&lt;&lt;

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

因为您已承诺 myClass 在名称空间 n1 中有一个朋友,但您实际上在全局名称空间中声明了该运算符。

【讨论】:

  • salam,1 soal dashtam,age betonid konakam konid mamnon misham.manzor az You must have a total score of 1000 in at least 200 non-community wiki answers to achieve this badge. chie?be chesoal haie non-community wiki migan.khaheshan javab bede.harchi serch kardam motavajeh nashodam.Email:eh。 taghdisi@gmail.com
  • @ehsan:阅读thisthis 就是一个例子。您可以在问题的右下角看到短语community wiki
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-27
  • 2021-03-04
  • 1970-01-01
  • 1970-01-01
  • 2017-08-26
  • 2013-06-09
  • 1970-01-01
相关资源
最近更新 更多