前言
本篇文章主要介绍了C++运算符重载
1.运算符重载的概念
基本概念:对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。
运算符重载的基本格式: 返回值类型 operator运算符 (参数列表)
大多数运算符可以被重载 不能重载的运算符只有5个:
运算符名称 | 运算符 |
---|
成员访问运算符 | . | 成员指针访问运算符 | .* | 域运算符 | :: | 长度运算符 | sizeof | 条件运算符 | ?: |
2.运算符重载的两种方式
2.1 使用成员函数重载运算符(类内重载)
#include <iostream>
#include <string>
using namespace std;
class A{
public:
A(int money = 0){
this->money = money;
}
int getMoney(){
return this->money;
}
A operator+(A &other){
return A(this->money + other.money);
}
private:
int money;
};
int main() {
A a1(100);
A a2(200);
A a3;
cout << "begin:" << a3.getMoney() << endl;
a3 = a1 + a2;
cout << "end:" << a3.getMoney() << endl;
return 0;
}
2.2 使用友元函数重载运算符(类外重载)
#include <iostream>
#include <string>
using namespace std;
class A{
public:
A(int money = 0){
this->money = money;
}
int getMoney(){
return this->money;
}
friend A operator+(const A a1,const A a2){
return A(a1.money+a2.money);
}
private:
int money;
};
int main() {
A a1(100);
A a2(200);
A a3;
cout << "begin:" << a3.getMoney() << endl;
a3 = a1 + a2;
cout << "end:" << a3.getMoney() << endl;
return 0;
}
3.几种运算符重载
3.1 赋值运算符重载
#include <iostream>
#include <string.h>
#include <string>
#include <sstream>
using namespace std;
class A{
public:
A(int money = 0,const char *name = ""){
this->money = money;
this->name = new char[strlen(name)+1];
strcpy(this->name, name);
}
~A(){
if (this->name) {
delete name;
}
}
int getMoney(){
return this->money;
}
string getInfo(){
stringstream ret;
ret << "name:" << name << "\tmoney:" << money;
return ret.str();
}
A &operator=(const A &other){
this->money = other.money;
return *this;
}
friend A operator+(const A &a1,const A &a2){
return A(a1.money+a2.money);
}
private:
int money;
char *name;
};
int main() {
A a1(100,"a1");
A a2(200,"a2");
A a3(0,"a3");
cout << "begin:" << a3.getInfo() << endl;
a3 = a1 + a2;
cout << "end:" << a3.getInfo() << endl;
return 0;
}
3.2 关系运算符的重载
bool operator>(const A &other){
bool ret = false;
if (this->money > other.money) {
ret = true;
}
return ret;
}
3.3 插入运算符(>>)和 提取运算符(<<)的重载
这里一般采用友元函数的形式重载(成员函数重载后写法是反的:a << cout)
friend istream &operator>>(istream &is, A &a1){
is >> a1.money;
return is;
}
friend ostream &operator<<(ostream &os, const A &a1){
os << a1.name << "\t" << a1.money;
return os;
}
int main() {
A a1(100,"a1");
A a2(200,"a2");
A a3(0,"a3");
a3 = a1 + a2;
cout << a1 << endl << a2 << endl << a3 << endl;
cin >> a1;
cout << a1;
return 0;
}
3.4 前置运算符重载++ 和 后置运算符重载++
前置运算符,需要引用返回,不需要参数。返回自增后的值,且返回的是一个左值 ; 后置++,不需要引用返回,需要参数区分。返回自增前的值,且返回的是一个右值。
A &operator++(){
this->money++;
return *this;
}
const A operator++(int tmp){
A a(this->money,this->name);
this->money++;
return a;
}
int main() {
A a1(100,"a1");
A a2(200,"a2");
A a3(0,"a3");
a3 = a1 + a2;
cout << a3 << endl;
cout << ++a3 << endl;
cout << a3++ << endl;
return 0;
}
|