2

I have a class within a namespace like following. 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;
}

On Compilation, I am getting following error.

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

How do I get past the errors?

  • Maybe the problem it's the name of stream, in cpp you wrote str and in the header file stream. Also did you tried to put friend in cpp? – Sergio Izquierdo Apr 09 '17 at 09:08
  • @Serizba: No, You can even remove name `stream` and just leave the definition only by types. – masoud Apr 09 '17 at 09:12

1 Answers1

3

You can define the operator << inside the namespace which myClass is defined:

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

Because you've promised myClass has a friend in name-space n1 but you actually declare the operator in global name-space.

masoud
  • 55,379
  • 16
  • 141
  • 208
  • 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 Jul 17 '17 at 07:09
  • @ehsan: Read [this](https://meta.stackexchange.com/tags/community-wiki/info). and [this](https://stackoverflow.com/questions/1642028/what-is-the-operator-in-c) is an example. You can see phrase `community wiki` at bottom-right of the question. – masoud Jul 17 '17 at 12:29