C++之类的友元函数

原文地址

【友元函数在实际开发中较少使用】

class Student{
private:
	string name;
	int age;
	float score;
	//const成员变量
	const string school;
	//定义静态成员变量
	static int number; 
	static float total;
public:
	//Student(string name,int age,float score);
	//有const成员变量,必须有参数初始化列表,
	Student(string name,int age,float score,string s):name(name),age(age),score(score),school(s){
		number++;
		total += score;
	}
	//拷贝构造函数中,const成员变量的初始化,用初始化列表
	Student(const Student & s):school(s.school){
		this ->name = s.name;
		this ->age = s.age;
		this ->score = s.score;
		number++;
		total += score;
	};
	~Student();
	void setSchool(string s);
	void setName(string n);
	string getName()const;
	void setAge(int a);
	friend void fsetAge(Student &s);
	int getAge() const;
	void setScore(float s);
	float getScore() const;
	void say() const;
	//say()函数也可以用 friend函数重写
	friend void fsay(const Student &s);
	static float getAverage();
	
	//运算符的重载
	//bool operator== (const Student &s) const;
	//用友元函数重载等于 运算符
	friend bool operator== (const Student &s,const Student&s1);
};



友元函数的定义:

//友元函数
void fsay(const Student &s){
	cout << s.name << " : " << s.age <<" : " <<s.score << endl;
}

void fsetAge(Student &s){
	s.age = 334312;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值