zhu@crabcake.cs.jhu.edu (Benjamin Zhu) (01/22/90)
------------------------------------------------ When I am doing programming in C++ with AT&T release 2.0, I have some trouble in declaring class member functions as friend functions. Usually, it is better to define some member functions of one class, as friend functions of another class, than to define the whole class as a friend of the other class. However, it seems hard to use the first method, whereas the second scheme works all the time. Here is a simple example. ----------------------------------------------------------------------- #include <stream.h> class B; // forward definition B& B::operator=(B&); // error: class B undefined class A { friend B& B::operator=(B&); // error: class B undefined public: A(int x) : a(x) {} private: int a; }; class B { public: B(int x) : b(x) {} B& operator=(B& y) // coding is deliberately nasty to test friend functions { b.a = y.a; } private: A b; }; main() { B b1(10), b2; b2 = b1; } ---------------------------------------------------------------------------- I just need to give access privileges for the private members in A to one member function, B& operator=(B&), in class B. However, this chunk of code does not work. The C++ translator reports that class B is undefined, when B& operator=(B&) is declared as a friend function of A. Notice, I have used forward definition for class B. O.K., let's give another shot. I swap the order of declarations for class A and B. I get ---------------------------------------------------------------------------- #include <stream.h> class A; class B { public: B(int x) : b(x) {} B& operator=(B& y) // deliberately nasty code to test friend functions { b.a = y.a; } private: A b; // error: A size unknown }; class A { friend B& B::operator=(B&); public: A(int x) : a(x) {} private: int a; }; main() { B b1(10), b2; b2 = b1; } ---------------------------------------------------------------------------- This time, it does not work either. The translator reports that the size of class A is unknown when class B is declared. Thus, my forward definition for class A is useless. On the other hand, when I declare class B as a friend class of A, everything is fine. Does anyone on the net have similar experience, and find the solution to get around this problem? According to the description on Lipmann's ``C++ Prime'', I believe this should be possible. Maybe someone can enlighten me.