Click to See Complete Forum and Search --> : friends and operators


Joerg Hansen
April 22nd, 1999, 07:04 AM
I have problems with Visual C++ 6.0 SP2 and NT 4.0 SP3 compiling this code:

#include <string>
using namespace std;
class Test
{
friend bool operator==( const Test& lhs, const Test& rhs );
private:
string s;
};
bool operator==( const Test& lhs, const Test& rhs )
{ return ( lhs.s == rhs.s ); }



I always receive a C2248-compiler-error. This is strange because I can compile it without any problems with VC 5.0 on NT or egcs on Linux.

Another strange thing: I can compile the inline-version

#include <string>
using namespace std;
class Test
{
friend bool operator==( const Test& lhs, const Test& rhs )
{ return ( lhs.s == rhs.s ); }
private:
string s;
};



as well as the no-namespace-version

#include <string>
class Test
{
friend bool operator==( const Test& lhs, const Test& rhs );
private:
std::string s;
};
bool operator==( const Test& lhs, const Test& rhs )
{ return ( lhs.s == rhs.s ); }



Any ideas? Perhaps something in the compiler settings? Or is it just a compiler-bug?

Any help is much appreciated

Joerg

April 22nd, 1999, 09:10 AM
It's a bug. Declaring a friend function immediately below a 'using namespace std;' directive causes this problem (there is a bug report for it on the Microsoft web site).

The best workaround is not to use the 'using namespace std;' directive. This should really not be used in header files because it opens the whole std namespace for all subsequently included headers, which kind of defeats the object of namespaces. In headers, always use the explicit namespace prefix for names. It is best avoided in source files too. In source files, put a using declaration at the top of the file (below the headers) for each name used:

Header (.h) files:

#include <string>
// using namespace std; // Don't use
class Test
{
friend bool operator==( const Test& lhs, const Test& rhs );
private:
std::string s; // use explicit namespace prefix
};
bool operator==( const Test& lhs, const Test& rhs )
{ return ( lhs.s == rhs.s ); }

Source (.cpp) files:

#include <string>
// using namespace std; // don't use.
using std::string; // prefer using declaration for each name

class Test
{
friend bool operator==( const Test& lhs, const Test& rhs );
private:
string s;
};
bool operator==( const Test& lhs, const Test& rhs )
{ return ( lhs.s == rhs.s ); }

Hope this helps,

Dave Lorde