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;
}




你可能感兴趣的:(C++之类的友元函数)