making ostream& operator<< a friend function of a class in a namespace

T

Tim Partridge

I want operator<< to be a friend function of a class inside a namespace, but
I don't know how. For example:

#include <iostream>

namespace ns {
class foo {
public:
// there is something wrong with the line below, but I don't
know how to fix it. I think I need to
// specify the namespace and class for the operator<<, but if I
write std::eek:stream::eek:perator<<
// i get all sorts of errors I don't understand.
friend std::eek:stream& operator<<( std::eek:stream &stream, const foo
&f );
private:
int i;
};
}

std::eek:stream& operator<<( std::eek:stream &stream, const ns::foo &f ) {
stream << f.i; // compiler complains i is private
return stream;
}

int main(int argc, char* argv[]) {
return 0;
}
 
S

Sumit Rajan

Tim Partridge said:
I want operator<< to be a friend function of a class inside a namespace, but
I don't know how. For example:

#include <iostream>

namespace ns {
class foo {
public:
// there is something wrong with the line below, but I don't
know how to fix it. I think I need to
// specify the namespace and class for the operator<<, but if I
write std::eek:stream::eek:perator<<
// i get all sorts of errors I don't understand.
friend std::eek:stream& operator<<( std::eek:stream &stream, const foo
&f );
private:
int i;
};
}

std::eek:stream& operator<<( std::eek:stream &stream, const ns::foo &f ) {
stream << f.i; // compiler complains i is private
return stream;
}

int main(int argc, char* argv[]) {
return 0;
}


#include <iostream>

namespace ns {
class foo {
public:
foo(int t=45):i(t){}
friend std::eek:stream& operator<<( std::eek:stream &stream, const
foo& f );
private:
int i;
};
std::eek:stream& operator << ( std::eek:stream &stream, const ns::foo &f );
// or you could define the operator right here
}

std::eek:stream& ns::eek:perator<<( std::eek:stream &stream, const ns::foo &f ) {
stream << f.i;
return stream;
}

int main(int argc, char* argv[]) {
ns::foo f(4);
std::cout << f << '\n';
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top