C++学习(5):运算符重载

前言

运算符重载作为C++的一大特性,在实际使用中很常见,本文重点讲解常用的一些用法。

正文

1、什么是运算符重载?
类比函数重载的概念,即赋予一个已知操作符别的用途。
2、为什么要用运算符重载?
C++实现了对基本数据类型的操作,比如:“1+1”,"2==2"等。现在为了让自定义类型(对象)也能应用于运算符进行操作,于是引入了运算符重载。
3、运算符重载怎么实现?
看代码

// operatorTest.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<string>

class Student {
public:
    Student(std::string name, int age) {
        this->name = name;
        this->age = age;
    }

    //重载运算符==,以年龄判断Stu对象是否相等
    bool operator == (Student& a) { 
        return this->age == a.age;
    }

    //重载运算符<<,输出Stu对象的信息
    friend std::ostream& operator << (std::ostream& os, Student& a) {
        os << a.name << ":" << a.age << std::endl;
        return os;
    }

private:
    std::string name;
    int age;
};

int main()
{
    Student a("小明",12);
    Student b("小红",12);
    std::cout << ((a == b) ? "Y" : "N") << std::endl; //对象使用运算符
    std::cout << a << b << std::endl;                 //对象使用运算符
    return 0;
}


总结

要想将对象应用于运算符,就要实现运算符重载。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值