Thread: namspace and friend functions

  1. #1
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    Posts
    715

    namspace and friend functions

    I have following problem (linker error):

    In header file I defined namespace
    something like this:

    Code:
    namespace Klass{
    	
    	class Test
    	{
    	public:
    		int itsInt;
    	public:
    		void set(int);
    		void show();
    	
     friend Test operator +(Test &,Test &);
    	};
    
    }
    In second i have this:

    Code:
    #include "Name.h"
    #include <iostream>
    using namespace Klass;
    using namespace std;
    
    void Test::set(int i)
    {
    	itsInt=i;
    }
    
    void Test::show()
    {
    	cout<<itsInt;
    }
    Test operator +(Test &A,Test &B)//Test Klass::operator+(....)
    
    {
    	Test tmp;
    	tmp.itsInt=A.itsInt+B.itsInt;
    	return tmp;
    }
    And finally in Main file I have:

    Code:
    #include "Name.h"
    
    using namespace Klass;
    
    int main()
    {
    	Test A;
    	A.set(2);
    	Test B;
    	B.set(3);
    	Test C=A+B;
    	C.show();
    	return 0;
    }
    If If try to compile and link I get linker error
    Main1.obj : error LNK2001: unresolved external symbol "class Klass::Test __cdecl Klass::operator+(class Klass::Test &,class Klass::Test &)" (??HKlass@@YA?AVTest@0@AAV10@0@Z)

    if I put Klass:: when I define operator + there are no error.

    My question is why this stuff with namespace is not working when I deal with friend functions and why I have to explicitly put

    Code:
    Test Klass::operator +(Test &A,Test &B)
    when I put using namespace Klass;
    What is the reason?
    Thanks in advance.

  2. #2
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    msvc 6 by any chance??
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  3. #3
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    Posts
    715

    reply

    Yes, exactly MS Visual C++ 6.0

  4. #4
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    Ahhhh!!!!

    * Friend functions *

    They are not your friend....trust me.

  5. #5
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    msvc 6 has some problems with friend funcs and also koenig lookup. Your code from first glance looks fine. To get around the problem rewrite operator + to use your classes public interface so it doesn't have to be a friend.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

Popular pages Recent additions subscribe to a feed