`
duoerbasilu
  • 浏览: 1482034 次
文章分类
社区版块
存档分类
最新评论

C++ 友元函数与友元类

 
阅读更多

友元函数

类的私有数据成员只能被类本身的成员函数访问。然而,这也有一个例外,这个类的友元函数也能访问这个类的私有数据成员.

#include <iostream>
using namespace std;

class Rectangle {
	int width, height;

public:
	Rectangle(int w = 1, int h = 1):width(w),height(h){} 
	friend void display(Rectangle &);
};

void display(Rectangle &r) {
	cout << r.width * r.height << endl;
}

int main () {
	Rectangle rect(5,10);
	display(rect);
	return 0;
}

友元函数总结:

友元函数不能是任何类的成员函数,但友元函数能访问友元关系类的私有数据成员

因为友元函数不能是任何类的数据成员,所以不能通过点操作符来调用

友元类

就向友元函数一样我们也可以有一个友元类,这个友元类能访问有友元关系类的其它私有数据成员。

#include <iostream>
using namespace std;

class Square;

class Rectangle {
	int width, height;

public:
	Rectangle(int w = 1, int h = 1):width(w),height(h){} 
	void display() {
		cout << "Rectangle: " << width * height << endl;
	};
	void morph(Square &);
};

class Square {
	int side;

public:
	Square(int s = 1):side(s){} 
	void display() {
		cout << "Square: " << side * side << endl;
	};
	friend class Rectangle;
};

void Rectangle::morph(Square &s) {
	width = s.side;
	height = s.side;
}

int main () {
	Rectangle rec(5,10);
	Square sq(5);
	cout << "Before:" << endl;
	rec.display();
	sq.display();

	rec.morph(sq);
	cout << "\nAfter:" << endl;
	rec.display();
	sq.display();
	return 0;
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics