friendly assignment operator

This is a discussion on friendly assignment operator within the C++ Programming forums, part of the General Programming Boards category; I'm having difficulty writing a friend operator, checkout the code below. The first operator compiles fine, but the second (the ...

  1. #1
    Registered User
    Join Date
    Dec 2002
    Posts
    162

    friendly assignment operator

    I'm having difficulty writing a friend operator, checkout the code below. The first operator compiles fine, but the second (the “=” operator) gives me a bunch of errors (first of which says “error C2801: 'operator =' must be a non-static member” in VC++ 2003). Is it illegal to define a friend operator for assignment? Thanks.

    Code:
    class A {
    public:
    
    	int x;
    };
    
    class B {
    public:
    
    	friend A& operator += (A &a, const B &b) {
    		a.x = 1;
    		return a;
    	}
    
    	friend A& operator = (A &a, const B &b) { // is this legal?
    		a.x = 2;
    		return a;
    	}
    };
    We haven't inherited Earth from our parents; instead we have borrowed her from our children - old Indian saying.

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    5,838
    Assignment operator can only be a member function of the class.

  3. #3
    The larch
    Join Date
    May 2006
    Posts
    3,573
    And in addition, (a method in) B just can't claim to be a friend of A to access its private members. Friendship works the other way: class A has to say it trusts (a method in) B, before B has any right's to A's data.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Crazy Assignment Operator Semantics
    By SevenThunders in forum C++ Programming
    Replies: 7
    Last Post: 01-22-2009, 12:08 PM
  2. Assignment Operator, Memory and Scope
    By SevenThunders in forum C++ Programming
    Replies: 47
    Last Post: 03-31-2008, 06:22 AM
  3. Smart pointer class
    By Elysia in forum C++ Programming
    Replies: 63
    Last Post: 11-03-2007, 07:05 AM
  4. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  5. operator overloading and dynamic memory program
    By jlmac2001 in forum C++ Programming
    Replies: 3
    Last Post: 04-06-2003, 11:51 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21