C++学习笔记4——类的封装(2)
简介:
重载的运算符是具有特殊名字的函数:它们的名字由关键字operator和其后要定义的运算符号共同组成。其中一元运算符有一个参数,二元运算符有两个参数。
可以被重载的运算符 | |||||
+ | - | * | / | % | ^ |
& | | | ~ | ! | , | = |
< | > | <= | >= | ++ | -- |
<< | >> | == | != | && | || |
+= | -= | /= | %= | ^= | &= |
|= | *= | <<= | >>= | [] | () |
-> | ->* | new | new[] | delete | delete[] |
不能被重载的运算符 | |||||
:: | .* | . | ? : |
PS:
&&和||运算符无法实现短路保护。
类型:
定义运算符重载时可定义为成员函数或者普通的非成员函数。
判断依据:
1、赋值(=)、下标([])、调用(())和成员访问箭头(->)运算符必须是成员。
2、复合赋值运算符一般来说是成员,但并非必须。
3、改变对象状态的运算符或者与给定类型密切相关的运算符,如递增、递减和解引用运算符通常应该是成员。
4、具有对称性的运算符可能转换任意一端的运算对象,例如算数、相等性、关系和位运算符等,通常应该是普通非成员函数。
5、输入和输出运算符必须是非成员函数。
Demo:
#pragma once #ifndef _COMPLEXNUMBER_ #define _COMPLEXNUMBER_ #include <iostream> class complexNum { friend std::ostream& operator<<(std::ostream &out, complexNum &rhs); friend std::istream& operator>>(std::istream &in, complexNum &rhs); public: complexNum(int real = 0, int image = 0); complexNum(const complexNum &obj); public: complexNum& operator=(const complexNum &rhs); complexNum operator+(const complexNum &rhs); complexNum& operator++(void); //前置++ complexNum operator++(int); //后置++,需要一个int的占位符 complexNum& operator+=(const complexNum &rhs); bool operator>(const complexNum &rhs); private: int real; int image; }; #endif
#include "complexNumber.h" complexNum::complexNum(int real, int image) :real(real), image(image){} complexNum::complexNum(const complexNum &obj) : real(obj.real), image(obj.image){} std::ostream& operator<<(std::ostream &out, complexNum &rhs) { out << rhs.real; if (rhs.image >= 0) out << "+"; out << rhs.image << "i" << std::endl; return out; } std::istream& operator>>(std::istream &in, complexNum &rhs) { return in >> rhs.real >> rhs.image; } complexNum& complexNum::operator=(const complexNum &rhs) { this->real = rhs.real; this->image = rhs.image; return *this; } complexNum complexNum::operator+(const complexNum &rhs) { complexNum tmp; tmp.real = this->real + rhs.real; tmp.image = this->image + rhs.image; return tmp; } complexNum& complexNum::operator++(void) { this->real++; this->image++; return *this; } complexNum complexNum::operator++(int) { complexNum tmp = *this; this->real++; this->image++; return tmp; } complexNum& complexNum::operator+=(const complexNum &rhs) { this->operator+(rhs); return *this; } bool complexNum::operator>(const complexNum &rhs) { if (this->real > rhs.real) return true; else if (this->real < rhs.real) return false; else { if (this->image > rhs.image) return true; else return false; } }