前言
运算符重载作为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;
}
总结
要想将对象应用于运算符,就要实现运算符重载。