• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

cynchanpin

  • 博客园
  • 联系
  • 订阅
  • 管理

View Post

C++之类的比較运算符的重载

比較运算符的重载通常有两种方式:

第一:作为成员函数重载

曾经几章的Student类为例:

<span style="font-family:Microsoft YaHei;font-size:18px;">class Student{
private:
	string name;
	int age;
	float score;
	//const成员变量
	const int max_length;
	//定义静态成员变量
	static int number; 
	static float total;
public:
	//Student(string name,int age,float score);
	//有const成员变量,必须有參数初始化列表,
	Student(string name,int age,float score):name(name),age(age),score(score),max_length(3){
		number++;
		total += score;
	}
	//拷贝构造函数中,const成员变量的初始化,用初始化列表
	Student(const Student & s):max_length(3){
		this ->name = s.name;
		this ->age = s.age;
		this ->score = s.score;
		number++;
		total += score;
	};
	~Student();
	void setName(string n);
	string getName()const;
	void setAge(int a);
	int getAge() const;
	void setScore(float s);
	float getScore() const;
	void say() const;
	static float getAverage();
	
	//运算符的重载
	bool operator== (const Student &s) const;
	//用友元函数重载等于 运算符
	//friend bool operator== (const Student &s,const Student&s1);
};
</span>
这里能够把(opetator==)理解为"成员函数名"。

bool Student::operator==(const Student &s) const {
	return this->name == s.name && this->age == s.age && this ->score == s.score;
}

第二:作为友元函数重载

 bool operator== (const Student &s,const Student&s1){
	 return (s.age == s1.age && s.name == s1.name && s.score == s1.score);
}




posted on 2017-07-13 10:30  cynchanpin  阅读(328)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3