All pastes #332003 Raw Edit

Anonymous

public cpp v1 · immutable
#332003 ·published 2007-01-29 17:56 UTC
rendered paste body
// Fig. 10.15: fig10_15.cpp// Friends can access private members of a class.#include <iostream>using std::cout;using std::endl;// Count class definitionclass Count{	friend void setX(Count &, int); // friend declarationpublic:	Count()		: x(0) // initialize x to 0	{		// empty body	} // end constructor Count	// output x	void print() const	{		 cout << x << endl;	} // end function printprivate:	int x; // date member}; // end class Count// function setX can modify private date of Count// because setX is declared as a friend of Count (line 10)void SetX(Count &c, int val){	c.x = val; // allowed because setX is a friend of Count} // end function setXint main(){	Count counter; // create Count object	cout << "counter.x after instantiation: ";	counter.print();	setX(counter, 8); // set x using a friend function	cout << "counter.x after call to setX friend function: ";	counter.print();	return 0;} // end main