比較运算符的重载通常有两种方式:
第一:作为成员函数重载
曾经几章的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);
}