一、C++运算符重载“==”
①不允许用户自定义新的运算符,只能对已有的运算符进行重载
②重载运算符不能改变运算符操作数的个数
③不能改变运算符的优先级
④不能改变运算符的结合性
⑤不能有默认的参数
#include<iostream>
using namespace std;
class CStudent
{
private:
string pname;
int page;
public:
CStudent(string name,int age)
{
pname = name;
page = age;
}
bool operator == (CStudent &stud)
{
if(pname == name&&page == age)
{
return true;
}
return false;
}
};
int main()
{
CStudent stud1("张三",18);
CStudent stud2("李四",20);
CStudent stud3("张三",18);
if(stud1 == stud2)
{
cout << "p1和p2相等" <<endl;
}
else
{
cout << "p1和p2不相等" <<endl;
}
if(stud1 == stud3)
{
cout << "p1和p3相等" <<endl;
}
else
{
cout << "p1和p3不相等" <<endl;
}
return 0;
}
二、子类继承父类的私有成员
在父类中创建一个公有函数,来访问其私有成员,然后在派生类中再创建一个函数来获得父类中访问其私有成员的函数返回值。这样就可以完成子类访问父类私有成员获得其值。
#include<iostream>
#include<string>
using namespace std;
class CStudent()
{
char *name;
char sex;
int num;
int age;
};
class xiaostudent : public CStudent
{
public:
int shuxue;
int yuwen;
private:
int music = 90;
public:
int chengji()
{
int *a = &music;
return *a;
}
};
class zhongstudent : public xiaostudent
{
public:
int wuli;
int huaxue;
int cj = chengji();
}
int main()
{
zhongstudent zhangsan;
cout << zhangsan.cj << endl;
return 0;
}