operator应用分两种:1.重载运算符;2.实现对象类型转换(网上找的,没懂什么意思)
代码:
#include <iostream>
using namespace std;
//重载运算符
class Student {
private:
string m_name; //姓名
int m_age; //年纪
int m_mathScores; //数学成绩
int m_chineseScores; //中文成绩
int m_englishScores; //英文成绩
public:
Student(string name, int age, int math_scores, int chinese_scores, int english_scores) {
this->m_name = name;
this->m_age = age;
this->m_mathScores = math_scores;
this->m_chineseScores = chinese_scores;
this->m_englishScores = english_scores;
}
bool operator==(const Student& stu) {
if(this->m_age == stu.m_age)
return true;
else
return false;
}
int operator+(const Student& stu) {
return this->m_mathScores + stu.m_mathScores;
}
};
//实现对象类型转化
class A {
public:
void setVar(double value) {
var = value;
}
operator int(){
cout<<__FUNCTION__<<endl;
return static_cast<int>(var);
}
private:
double var;
};
int main()
{
cout << "Hello World!" << endl;
Student stu_a("张三", 19, 65, 65, 65);
Student stu_b("李四", 19, 85, 85, 85);
if(stu_a == stu_b) {
cout<<"students a and b age equal"<<endl;
} else {
cout<<"students a and b age not equal"<<endl;
}
cout<<"students a and b math sum of scores : "<<stu_a + stu_b<<endl;
A func_a;
func_a.setVar(10.25);
cout<<func_a<<endl;//实际调用的是func.operator int()这个函数
return 0;
}