c ++ Third job: Class friend

 

C ++ Third job: Class friend

1, friend relationship provides a mechanism member functions among different classes or objects, data sharing functions among the members of the general class of functions. Popular to say that friendship is a class declaration other active function is his friend, enable them to get special access rights.
2, the friend function, the type used in the modified non-keyword friend member function. Although it is not a member of this class functions, but its function in the body can be private and protected members through an object name to access the class.

The following section of code for profit:

#include"oo.h"
using namespace std;
class A {
public:
A(int x = 0, int y = 0) :price(x), cost(y) {};
friend int profit(A& a);
private:
int price, cost;
};
int profit(A& a) {
return (a.price-a.cost);
}
int main() {
A pa(58, 32);
cout << "Profit is:";
cout << profit(pa) << endl;
return 0;
}

 

It declares its friend functions in class A, or a non-member function, so that you can access private members in the A category: original price and cost, which can be drawn subtracting profits. Its operating results are as follows:

 

 

 

 

If not declare a friend function, its nonmember functions can not access the private members of the class A, that is a friend to this keyword, the code will run error.

3, like the friend function, a class can be declared as another class friend class. If the class is a friend class A class B, then class A of all member functions are friend function class B, you can access private members and protected members of the class B.
The following code:

 

class A {
public:
A(int x = 0, int y = 0) :price(x), cost(y) {};
int getp() { return price; }
int getc() { return cost; }
friend class B;
private:
int price, cost;
};
class B {
public:
void show();
private:
A a;
};
void B::show() {
cout << "price is:" << a.getp()<< endl;
cout << "cost is:" << a.getc() << endl;
}
int main() {
B mb;
mb.show();
return 0;
}

 

Friend Note:

1, the friend relationship can not be transmitted;
2, friend relationship is unidirectional;
3, friend relationship is not inherited.

Guess you like

Origin www.cnblogs.com/zxsnh/p/11586621.html