Sign in to follow this  
beebs1

ostream operator & namespaces

Recommended Posts

Hiya,

I have a class inside a namespace, which declares an output stream operator as friend in a header file. I then have the operator definition inside a seperate source file.

For some reason the namespace is causing the compiler to decide it can't access the member variables of the class..

Something like this:
[code]
// BigInteger.h
#include <iostream>

namespace test {

class BigInteger
{
friend std::ostream& operator<<(std::ostream& stream, const BigInteger& bigInteger);

public: /* Etc. */

private:
int value;
};
}

// BigInteger.cpp
using namespace test;

/* All the method definitions... */

std::ostream& operator<<(std::ostream& stream, const BigInteger& bigInteger)
{
std::cout << bigInteger.value; // C2248 - Cannot access private member...
}
[/code]

Any ideas why this is happening? Removing the namespace allows it to compile.

Thanks!

Share this post


Link to post
Share on other sites
The easiest way to get this to compile is to put your function definition inside the test namespace. I.e.:
[code]
namespace test {
std::ostream& operator<<(std::ostream& stream, const BigInteger& bigInteger)
{
std::cout << bigInteger.value;
}
}
[/code]

Share this post


Link to post
Share on other sites
With G++, the following change compiles:

[source lang="cpp"]
std::ostream &test::operator<<(std::ostream &stream, const BigInteger &bigInteger)
{
std::cout << bigInteger.value;
}
[/source]

I believe because the friend prototype is declared within the test namespace, it is considered a different function to the same declared in the global namespace. Might be clearer to just define the method within the test namespace.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this