Jump to content
  • Advertisement
Sign in to follow this  
beebs1

ostream operator & namespaces

This topic is 2548 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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:

// 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...
}


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

Thanks!

Share this post


Link to post
Share on other sites
Advertisement
The easiest way to get this to compile is to put your function definition inside the test namespace. I.e.:

namespace test {
std::ostream& operator<<(std::ostream& stream, const BigInteger& bigInteger)
{
std::cout << bigInteger.value;
}
}

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!