C++ 友元(七)

32 篇文章 0 订阅
  1. 全局函数作为友元函数
    1. friend  类型 函数名(类名* 变量名);
  2. 类作为友元类
    1. friend class 类名;
  3. 类中的成员函数作为友元函数
    1.    friend void 类名::类中函数名();

#include<iostream>
#include<string>
using namespace std;

class building;

class room {
private:
	int rid;
	int num;
	building *d;
public:
	room(int rid, int num);
	void getAllInfo();
};

class building {
	//friend class room;
	friend void room::getAllInfo();
	friend void test(building* b1);
private:
	string name;
	string position;
	int rooms;
	int storeys;
public:
	building() {
		this->name = "abc";
		this->position="def";
		this->rooms=21;
		this->storeys =12;
	}
	building(string name,string position,int rooms,int storeys)
		:name(name),position(position),rooms(rooms),storeys(storeys) {
		
	}
	void getInfo() {
		cout<<"name: " << this->name << endl;
		cout << "position: " << this->position << endl;
		cout << "rooms: " << this->rooms << endl;
		cout << "storeys: " << this->storeys << endl;
	}
};

room::room(int rid, int num) {
	this->rid = rid;
	this->num = num;
	this->d = new building;
}

void room::getAllInfo() {
	cout << this->d->name << endl;
}

void test(building *b1) {
	building* b = new building("asdasd","asdqwd",12,21);
	b->getInfo();

	room* r = new room(1,2);
	r->getAllInfo();

	cout<<b1->name << endl;
}

int main() {
	building b1("asdasd", "asdqwd", 12, 21);
	test(&b1);
	system("pause");
	return EXIT_SUCCESS;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值