Subj : Re: Need help, please! To : borland.public.cpp.borlandcpp From : "Ed Mulroy [TeamB]" Date : Tue Nov 25 2003 06:52 pm Here is one. I'll be back with another in a few minutes. ------------------------------------------- C:\Lookat\q421 >type q421.cpp // partial declaration so the function // prototype of the operator will know // something of what the symbol 'ClassA' means class ClassA; // Function prototype for the operator // // You don't need a friend operator for two // class arguments because you already have // that from the member function. You may need // one for subtracting the class from an int. // // Note that this uses a reference, not an instance // (call by reference instead of by value) int operator - (int i1, const ClassA& obj2); class ClassA { private: int iMember; // Make class data private // If it were public then you would be // able to access it so why would you // need a friend function? public: // added constructor insures behavior // is always deterministic ClassA() : iMember(0) {} ClassA(int i) : iMember(i) {} // added accessor function, gets the value int Value() const { return iMember; } // added mutator function, changes the value void Value(int i) { iMember = i; } // note that this uses references, not instances ClassA operator - (const ClassA& Obj ) const { ClassA tmp; tmp.iMember = iMember - Obj.iMember; return tmp; } friend int operator - (int i1, const ClassA& obj2); // the function below is not needed because // it duplicates what the member function does // friend ClassA operator-(const ClassA Obj1, const ClassA Obj2); }; // because we now have the Value() member function, // we could get away from needing this to be a friend // however I'll write it to use iMember to illustrate that // a friend function works int operator - (int i1, const ClassA& obj2) { return i1 - obj2.iMember; // could have used obj2.Value() } #include using namespace std; int main() { ClassA obj1(5); ClassA obj2(3); ClassA result = obj1 - obj2; cout << "obj1.Value() = " << obj1.Value() << endl; cout << "obj2.Value() = " << obj2.Value() << endl; cout << "obj1.Value() - obj2.Value() = " << result.Value() << endl; cout << "17-obj2 Using friend: " << 17 - obj2 << endl; return 0; } C:\Lookat\q421 > C:\Lookat\q421 >bcc32 -WCR q421 Borland C++ 5.6.4 for Win32 Copyright (c) 1993, 2002 Borland Q421.CPP: Turbo Incremental Link 5.64 Copyright (c) 1997-2002 Borland C:\Lookat\q421 >q421 obj1.Value() = 5 obj2.Value() = 3 obj1.Value() - obj2.Value() = 2 17-obj2 Using friend: 14 C:\Lookat\q421 > ------------------------------------------- .. Ed ' > Bojidar Markov wrote in message > news:3fc3d0e3@newsgroups.borland.com... .