C++运算符、继承

一、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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值