c++ operator的应用

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值