By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,194 Members | 847 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,194 IT Pros & Developers. It's quick & easy.

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

P: n/a
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::ostream::operator<<
// i get all sorts of errors I don't understand.
friend std::ostream& operator<<( std::ostream &stream, const foo
&f );
private:
int i;
};
}

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

int main(int argc, char* argv[]) {
return 0;
}
Jul 22 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a

"Tim Partridge" <ed***@hotmail.com> wrote in message
news:pt*********************@twister01.bloor.is.ne t.cable.rogers.com...
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::ostream::operator<<
// i get all sorts of errors I don't understand.
friend std::ostream& operator<<( std::ostream &stream, const foo &f );
private:
int i;
};
}

std::ostream& operator<<( std::ostream &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::ostream& operator<<( std::ostream &stream, const
foo& f );
private:
int i;
};
std::ostream& operator << ( std::ostream &stream, const ns::foo &f );
// or you could define the operator right here
}

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

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

This discussion thread is closed

Replies have been disabled for this discussion.