C++ examples for Class:friend
Create friend square() function for Measure class
#include <iostream> using namespace std; class Measure/*from www . j a v a 2 s . c o m*/ { private: int feet; float inches; public: Measure() { feet = 0; inches = 0.0; } Measure(float fltfeet) //constructor (one arg) { //feet is integer part feet = static_cast<int>(fltfeet); inches = 12*(fltfeet-feet); //inches is what's left } Measure(int ft, float in) : feet(ft), inches(in) { } void showdist() { cout << feet << "\'-" << inches << '\"'; } friend Measure operator * (Measure, Measure); //friend }; //multiply d1 by d2 Measure operator * (Measure d1, Measure d2) { float fltfeet1 = d1.feet + d1.inches/12; //convert to float float fltfeet2 = d2.feet + d2.inches/12; float multfeet = fltfeet1 * fltfeet2; //find the product return Measure(multfeet); //return temp Measure } int main() { Measure dist1(3, 6.0); //make some distances Measure dist2(2, 3.0); Measure dist3; dist3 = dist1 * dist2; //multiplication dist3 = 10.0 * dist3; //mult and conversion //display all distances cout << "\ndist1 = "; dist1.showdist(); cout << "\ndist2 = "; dist2.showdist(); cout << "\ndist3 = "; dist3.showdist(); cout << endl; return 0; }