初识C++05:运算符重载

运算符重载

运算符重载基础#

函数重载(Function Overloading)可以让一个函数名有多种功能,在不同情况下进行不同的操作。运算符重载(Operator Overloading)也是一个道理,同一个运算符可以有不同的功能。

例子:用+号实现复数加法运算;成员函数重载运算符

Copy
#include <iostream> using namespace std; class complex{ public: complex(); complex(double real, double imag); public: //声明运算符重载 complex operator+(const complex &A) const; void display() const; private: double m_real; //实部 double m_imag; //虚部 }; complex::complex(): m_real(0.0), m_imag(0.0){ } complex::complex(double real, double imag): m_real(real), m_imag(imag){ } //实现运算符重载 complex complex::operator+(const complex &A) const{ return complex(this->m_real + A.m_real, this->m_imag + A.m_imag);//返回临时对象 } void complex::display() const{ cout<<m_real<<" + "<<m_imag<<"i"<<endl; } int main(){ complex c1(4.3, 5.8); complex c2(2.4, 3.7); complex c3; c3 = c1 + c2; c3.display();// 运行结果: 6.7 + 9.5i return 0; }

可以看出:运算符重载是通过函数实现的,它本质上是函数重载

运算符重载格式:

返回值类型 operator 运算符名称 (形参表列){
//TODO:
}

Copy
operator是关键字,专门用于定义重载运算符的函数。我们可以将`operator 运算符名称`这一部分看做函数名,对于上面的代码,函数名就是operator+

即是:运算符重载除了函数名不同,其他地方和函数没有什么区别;

当执行c3 = c1 + c2;语句时,编译器检测到+号左边(+号具有左结合性,所以先检测左边)是一个 complex 对象,就会调用成员函数operator+(),也就是转换为下面的形式:

c3 = c1.operator+(c2);

c1 是要调用函数的对象,c2 是函数的实参

全局内重载运算符:

运算符重载函数不仅可以作为类的成员函数,还可以作为全局函数。利用友元函数来实现(获取private属性,归属于全局函数的应用)

更改上述例子:

Copy
#include <iostream> using namespace std; class complex{ public: complex(); complex(double real, double imag); public: void display() const; //声明为友元函数 friend complex operator+(const complex &A, const complex &B); private: double m_real; double m_imag; }; complex operator+(const complex &A, const complex &B); complex::complex(): m_real(0.0), m_imag(0.0){ } complex::complex(double real, double imag): m_real(real), m_imag(imag){ } void complex::display() const{ cout<<m_real<<" + "<<m_imag<<"i"<<endl; } //在全局范围内重载+ complex operator+(const complex &A, const complex &B){ complex C; C.m_real = A.m_real + B.m_real; C.m_imag = A.m_imag + B.m_imag; return C; } int main(){ complex c1(4.3, 5.8); complex c2(2.4, 3.7); complex c3; c3 = c1 + c2; c3.display(); return 0; }

通过运算符重载,扩大了C++已有运算符的功能,使之能用于对象,更人性了hhh;

tip: 非静态成员函数后面加const(加到非成员函数或静态成员后面会产生编译错误,静态和非静态的区别就是,查看下面链接),表示成员函数隐含传入的this指针为const指针,决定了在该成员函数中,任意修改它所在的类的成员的操作都是不允许的(因为隐含了对this指针的const引用);唯一的例外是对于mutable修饰的成员。加了const的成员函数可以被非const对象和const对象调用,但不加const的成员函数只能被非const对象调用。静态函数和非静态函数的区别什么是mutable

运算符重载的规则#

  • 可以重载的运算符:+ - * / % ^ & | ~ ! = < > += -= = /= %= ^= &= |= << >> <<= >>= == != <= >= && || ++ -- , -> -> () [] new new[] delete delete[] ,自增自减运算符的前置和后置形式都可以重载

长度运算符sizeof、条件运算符: ?、成员选择符.和域解析运算符::不能被重载。

  • 重载不能改变运算符的优先级和结合性,如+-*/等运算符的优先级不会被改变;
  • 运算符重载函数不能有默认的参数,否则就改变了运算符操作数的个数(比如+号默认参数为1,结果肯定不对),这显然是错误的(有的博客说重载函数要有遵循固定数量的参数,和公认的相同)
  • 运算符重载函数既可以作为类的成员函数,也可以作为全局函数

将运算符重载函数作为类的成员函数时,二元运算符的参数只有一个,一元运算符不需要参数。之所以少一个参数,是因为这个参数是隐含的,是这个类对象本身;如上面的this,通过 this 指针隐式的访问 c1 的成员变量。

将运算符重载函数作为全局函数时,二元操作符就需要两个参数,一元操作符需要一个参数,而且其中必须至少有一个参数是对象,好让编译器区分这是程序员自定义的运算符,防止程序员修改用于内置类型的运算符的性质,比如:

Copy
int operator + (int a,int b){//显然错误,会造成歧义,改变内置类型的运算符的性质(别人设过的东西你别用) return (a-b); }

而如果上述的a或者b是一个对象,那么就是成立的;

同时,将运算符重载函数作为全局函数时,一般都需要在类中将该函数声明为友元函数。原因很简单,该函数大部分情况下都需要使用类的 private 成员。

  • 箭头运算符->、下标运算符[ ]、函数调用运算符( )、赋值运算符=只能以成员函数的形式重载。

重载数学运算符例子#

实际开发中重载数学运算符号非常常见,比如c++只是定义了复数的==,我们来实现复数的+,-,*,例子如下:

Copy
#include <iostream> #include <cmath> using namespace std; //复数类 class Complex{ public: //构造函数 Complex(double real = 0.0, double imag = 0.0): m_real(real), m_imag(imag){ } public: //运算符重载 //以全局函数的形式重载!!!!!!!!!!! friend Complex operator+(const Complex &c1, const Complex &c2); friend Complex operator-(const Complex &c1, const Complex &c2); friend Complex operator*(const Complex &c1, const Complex &c2); friend Complex operator/(const Complex &c1, const Complex &c2); friend bool operator==(const Complex &c1, const Complex &c2); friend bool operator!=(const Complex &c1, const Complex &c2); //以成员函数的形式重载!!!!!!!!!!!! Complex & operator+=(const Complex &c); Complex & operator-=(const Complex &c); Complex & operator*=(const Complex &c); Complex & operator/=(const Complex &c); public: //成员函数 double real() const{ return m_real; } double imag() const{ return m_imag; } private: double m_real; //实部 double m_imag; //虚部 }; //重载+运算符 Complex operator+(const Complex &c1, const Complex &c2){ return Complex c; c.m_real = c1.m_real + c2.m_real; c.m_imag = c1.m_imag + c2.m_imag; return c; } //重载-运算符 Complex operator-(const Complex &c1, const Complex &c2){ Complex c; c.m_real = c1.m_real - c2.m_real; c.m_imag = c1.m_imag - c2.m_imag; return c; } //重载*运算符 (a+bi) * (c+di) = (ac-bd) + (bc+ad)i Complex operator*(const Complex &c1, const Complex &c2){ Complex c; c.m_real = c1.m_real * c2.m_real - c1.m_imag * c2.m_imag; c.m_imag = c1.m_imag * c2.m_real + c1.m_real * c2.m_imag; return c; } //重载/运算符 (a+bi) / (c+di) = [(ac+bd) / (c²+d²)] + [(bc-ad) / (c²+d²)]i Complex operator/(const Complex &c1, const Complex &c2){ Complex c; c.m_real = (c1.m_real*c2.m_real + c1.m_imag*c2.m_imag) / (pow(c2.m_real, 2) + pow(c2.m_imag, 2)); c.m_imag = (c1.m_imag*c2.m_real - c1.m_real*c2.m_imag) / (pow(c2.m_real, 2) + pow(c2.m_imag, 2)); return c; } //重载==运算符 bool operator==(const Complex &c1, const Complex &c2){ if( c1.m_real == c2.m_real && c1.m_imag == c2.m_imag ){ return true; }else{ return false; } } //重载!=运算符 bool operator!=(const Complex &c1, const Complex &c2){ if( c1.m_real != c2.m_real || c1.m_imag != c2.m_imag ){ return true; }else{ return false; } } //重载+=运算符,开始有&符号 Complex & Complex::operator+=(const Complex &c){ this->m_real += c.m_real; this->m_imag += c.m_imag; return *this;//this就是一个指针,*解引用,返回的是this指向的对象 } //重载-=运算符 Complex & Complex::operator-=(const Complex &c){ this->m_real -= c.m_real; this->m_imag -= c.m_imag; return *this; } //重载*=运算符 Complex & Complex::operator*=(const Complex &c){ this->m_real = this->m_real * c.m_real - this->m_imag * c.m_imag; this->m_imag = this->m_imag * c.m_real + this->m_real * c.m_imag; return *this; } //重载/=运算符 Complex & Complex::operator/=(const Complex &c){ this->m_real = (this->m_real*c.m_real + this->m_imag*c.m_imag) / (pow(c.m_real, 2) + pow(c.m_imag, 2)); this->m_imag = (this->m_imag*c.m_real - this->m_real*c.m_imag) / (pow(c.m_real, 2) + pow(c.m_imag, 2)); return *this; } int main(){ Complex c1(25, 35); Complex c2(10, 20); Complex c3(1, 2); Complex c4(4, 9); Complex c5(34, 6); Complex c6(80, 90); Complex c7 = c1 + c2; Complex c8 = c1 - c2; Complex c9 = c1 * c2; Complex c10 = c1 / c2; cout<<"c7 = "<<c7.real()<<" + "<<c7.imag()<<"i"<<endl; cout<<"c8 = "<<c8.real()<<" + "<<c8.imag()<<"i"<<endl; cout<<"c9 = "<<c9.real()<<" + "<<c9.imag()<<"i"<<endl; cout<<"c10 = "<<c10.real()<<" + "<<c10.imag()<<"i"<<endl; c3 += c1; c4 -= c2; c5 *= c2; c6 /= c2; cout<<"c3 = "<<c3.real()<<" + "<<c3.imag()<<"i"<<endl; cout<<"c4 = "<<c4.real()<<" + "<<c4.imag()<<"i"<<endl; cout<<"c5 = "<<c5.real()<<" + "<<c5.imag()<<"i"<<endl; cout<<"c6 = "<<c6.real()<<" + "<<c6.imag()<<"i"<<endl; if(c1 == c2){ cout<<"c1 == c2"<<endl; } if(c1 != c2){ cout<<"c1 != c2"<<endl; } return 0; }

运行结果:

image-20220313193659481

选择是成员函数还是全局函数运算符重载#

看例子:

Copy
Complex(double real): m_real(real), m_imag(0.0){ } //转换构造函数 //重载+号运算符,设置成全局函数运算符重载 Complex operator+(const Complex &c1, const Complex &c2) ..... Complex c2 = c1 + 15.6;//正确 Complex c3 = 28.23 + c1;//正确

为什么要设置成全局运算符呢?

因为如果设置成成员函数,Complex c3 = 28.23 + c1;将会是错误的;

原理:因为是全局函数,保证了 + 运算符的操作数能够被对称的处理,存在转换构造函数编译器在检测到 Complex 和 double(小数默认为 double 类型)相加时,会先尝试将 double 转换为 Complex,或者反过来将 Complex 转换为 double(只有类型相同的数据才能进行 + 运算),如果都转换失败,或者都转换成功(产生了二义性),才报错。本例中,编译器会先通过构造函数Complex(double real);将 double 转换为 Complex,再调用重载过的 + 进行计算,整个过程类似于下面的形式:

image-20220313200108463

设置成成员函数:根据“+ 运算符具有左结合性”这条原则,Complex c3 = 28.23 + c1会被转换为Complex c3 = (28.23).operator+(c1),很显然这是错误的,因为 double 类型并没有以成员函数的形式重载 +。所以成员函数不能对此处理操作数;

为什么成员函数中不能用转换构造函数处理数据28.23为Complex(28.23),而全局函数可以?

C++ 只会对成员函数的参数进行类型转换,而不会对调用成员函数的对象进行类型转换,因为设置为成员函数,28.23不是函数的参数,是拥有该函数的类对象,调用的将是28.23这个double对象的重载+,明显是没有的该函数,会报错;而全局函数,那么调用的将是operator+(28.23, c1)这个函数,那么28.23,c1都是函数的参数,是可以调用转换构造函数的。

注意ψ(`∇´)ψ👀:运算符重载的初衷是给类添加新的功能,方便类的运算,它作为类的成员函数是理所应当的,是首选的!

但是因为有处理对称的需求,每个类都重载一下运算符,过于麻烦了,所以允许采用全局函数重载。所以我们知道:参数具有逻辑的对称性,我们采用全局函数定义;第一个(最左的)运算对象不出现类型转换,我们运算符重载定义为成员函数;

C++ 规定,箭头运算符->、下标运算符[ ]、函数调用运算符( )、赋值运算符=只能以成员函数的形式重载。

重载<<和>>运算符#

标准库本身已经对左移运算符<<和右移运算符>>分别进行了重载,使其能够用于不同数据的输入输出,但是输入输出的对象只能是 C++ 内置的数据类型(例如 bool、int、double 等)和标准库所包含的类类型(例如 string、complex、ofstream、ifstream 等)

有时候我们想重载输入输出符号,可以输入输出我们自己定义的类型,看下例,一样采用对复数的重载,基于上面的例子,加多实现输入输出:

Copy
//complex类中定义输入输出为友函数(只能定义为友函数),供全局可以使用,因为重载函数中用到了 complex 类的 private 成员变量,定义为成员函数依据左结合性,会非常奇怪,>>的左边需要一个complex类对象; friend istream & operator>>(istream & in, complex & A); friend ostream & operator<<(ostream & out, complex & A); //重载输入运算符 istream & operator>>(istream & in, complex & A){ in >> A.m_real >> A.m_imag;//输入,基于标准库的类; return in;//返回引用更方便再次使用,可以cin>>c1>>c2 ,连续输入两个对象;因为(cin>>c1)又是一个cin又可以cin>>c2; } //重载输出运算符 ostream & operator<<(ostream & out, complex & A){ out << A.m_real <<" + "<< A.m_imag <<" i ";//输出,基于标准库的类 return out;//与上同理 } //main函数中: complex c1, c2, c3; cin>>c1>>c2;//具体逻辑:>>(cin, c1), >>(cin, c2) c3 = c1 + c2; cout<<"c1 + c2 = "<<c3<<endl;

image-20220313210116716

输入函数定义为全局函数,相当于:operator>>(cin , c);

重载[](下标运算符)#

C++ 规定,下标运算符[ ]必须以成员函数的形式进行重载,重载函数在类中的声明如下:

返回值类型 & operator[ ] (参数);

或者:

const 返回值类型 & operator[ ] (参数) const;

使用第一种声明方式,[ ]不仅可以访问元素,还可以修改元素。使用第二种声明方式,[ ]只能访问而不能修改元素。在实际开发中,我们应该同时提供以上两种形式,这样做是为了适应 const 对象,因为通过 const 对象只能调用 const 成员函数,如果不提供第二种形式,那么将无法访问 const 对象的任何元素

例子:

Copy
#include <iostream> using namespace std; class Array{ public: Array(int length = 0); ~Array(); public: int & operator[](int i); const int & operator[](int i) const; public: int length() const { return m_length; } void display() const; private: int m_length; //数组长度 int *m_p; //指向数组内存的指针 }; Array::Array(int length): m_length(length){ if(length == 0){ m_p = NULL; }else{ m_p = new int[length]; } } Array::~Array(){ delete[] m_p; } int& Array::operator[](int i){ return m_p[i]; } const int & Array::operator[](int i) const{//注意两个const return m_p[i]; } void Array::display() const{ for(int i = 0; i < m_length; i++){ if(i == m_length - 1){ cout<<m_p[i]<<endl; }else{ cout<<m_p[i]<<", "; } } } int main(){ int n; cin>>n; Array A(n); for(int i = 0, len = A.length(); i < len; i++){ A[i] = i * 5; } A.display(); const Array B(n); cout<<B[n-1]<<endl; //访问最后一个元素 return 0; }

结果:

image-20220314003346106

tip:const加在函数前后的区别

重载++和--#

前置和后置++例子:

Copy
#include <iostream> #include <iomanip> using namespace std; //秒表类 class stopwatch{ public: stopwatch(): m_min(0), m_sec(0){ } public: void setzero(){ m_min = 0; m_sec = 0; } stopwatch run(); // 运行 stopwatch operator++(); //++i,前置形式 stopwatch operator++(int); //i++,后置形式,不写参数名形式 friend ostream & operator<<( ostream &, const stopwatch &); private: int m_min; //分钟 int m_sec; //秒钟 }; stopwatch stopwatch::run(){ ++m_sec; if(m_sec == 60){ m_min++; m_sec = 0; } return *this; } stopwatch stopwatch::operator++(){ return run(); } stopwatch stopwatch::operator++(int n){ stopwatch s = *this; // 拷贝构造 run(); return s; // 符合 用完再加的思想 } ostream &operator<<( ostream & out, const stopwatch & s){ out<<setfill('0')<<setw(2)<<s.m_min<<":"<<setw(2)<<s.m_sec; return out; } int main(){ stopwatch s1, s2; s1 = s2++; cout << "s1: "<< s1 <<endl; cout << "s2: "<< s2 <<endl; s1.setzero(); s2.setzero(); s1 = ++s2; cout << "s1: "<< s1 <<endl; cout << "s2: "<< s2 <<endl; return 0; }

operator++ (int n) 函数实现自增的后置形式,返回值是对象本身,但是之后(过了这个表达式)再次使用该对象时,对象自增了,所以在该函数的函数体中,先将对象保存,然后调用一次 run() 函数,之后再将先前保存的对象返回(这个时候没有自增)。在这个函数中参数n是没有任何意义的,它的存在只是为了区分是前置形式还是后置形式。

结果:

image-20220314003655128

重载new和delete#

内存管理运算符 new、new[]、delete 和 delete[] 也可以进行重载,其重载形式既可以是类的成员函数,也可以是全局函数。一般情况下,内建的内存管理运算符就够用了,只有在需要自己管理内存时才会重载

new:

成员函数形式:

Copy
void * className::operator new( size_t size ){ //TODO: }

全局函数形式:

Copy
void * operator new( size_t size ){ //TODO: }

可以看出:两种重载形式的返回值相同,都是void *类型,并且都有一个参数,为size_t类型。在重载 new 或 new[] 时,无论是作为成员函数还是作为全局函数,它的第一个参数必须是 size_t 类型。size_t 表示的是要分配空间的大小,对于 new[] 的重载函数而言,size_t 则表示所需要分配的所有空间的总和。(size_t 在头文件 中被定义为typedef unsigned int size_t;,也就是无符号整型)

重载函数也可以有其他参数,但都必须有默认值,并且第一个参数的类型必须是 size_t。

delete:

成员函数:

Copy
void className::operator delete( void *ptr){ //TODO: }

全局函数:

Copy
void operator delete( void *ptr){ //TODO: }

两种重载形式的返回值都是 void 类型,并且都必须有一个 void 类型的指针作为参数,该指针指向需要释放的内存空间;

当我们以类成员重载了new和delete函数,使用例子:

Copy
C * c = new C; //分配内存空间 //TODO: delete c; //释放内存空间

如果类中没有定义 new 和 delete 的重载函数,那么会自动调用内建的 new 和 delete 运算符;

例子:

Copy
#include<iostream> using namespace std; class Foo { public: int _id; long _data; string _str; public: Foo():_id(0){cout<<"default ctor.this="<<this<<" id="<<_id<<endl;} Foo(int i):_id(i){cout<<"ctor.this="<<this<<" id="<<_id<<endl;} ~Foo() {cout<<"dtor.this="<<this<<" id="<<_id<<endl;} static void* operator new(size_t size); static void operator delete(void* pdead,size_t size); static void* operator new[](size_t size); static void operator delete[](void* pdead,size_t size); }; void* Foo::operator new(size_t size) { Foo* p = (Foo *)malloc(size); cout<<"调用了Foo::operator new"<<endl; return p; } void Foo::operator delete(void *pdead,size_t size) { cout<<"调用了Foo::operator delete"<<endl; free(pdead); } void* Foo::operator new[](size_t size) { Foo* p = (Foo*)malloc(size); cout<<"调用了Foo::operator new[]"<<endl; return p; } void Foo::operator delete[](void *pdead, size_t size) { cout<<"调用了Foo::operator delete[]"<<endl; free(pdead); } int main() { Foo* pf = new Foo(7); Foo* pf1 = new Foo[2]; delete pf; delete[] pf1; }

结果:

image-20220314080651624

重载()#

直接看例子:将 double类型强制转换运算符 进行重载

Copy
#include <iostream> using namespace std; class Complex { double real, imag; public: Complex(double r = 0, double i = 0) :real(r), imag(i) {}; operator double() { return real; } //重载强制类型转换运算符 double }; int main() { Complex c(1.2, 3.4); cout << (double)c << endl; //输出 1.2 double n = 2 + c; //等价于 double n = 2 + c. operator double() cout << n; //输出 3.2 }

类型强制转换运算符是单目运算符,也可以被重载,但只能重载为成员函数,不能重载为全局函数。经过适当重载后,(类型名)对象这个对 对象 进行强制类型转换的表达式就等价于对象.operator 类型名(),即变成对运算符函数的调用

重载强制类型转换运算符时,不需要指定返回值类型,因为返回值类型是确定的,就是运算符本身代表的类型,在这里就是 double。

重载后的效果是,第 13 行的(double)c等价于c.operator double()

有了对 double 运算符的重载,在本该出现 double 类型的变量或常量的地方,如果出现了一个 Complex 类型的对象,那么该对象的 operator double 成员函数就会被调用,然后取其返回值使用。

例如第 14 行,编译器认为本行中c这个位置如果出现的是 double 类型的数据,就能够解释得通,而 Complex 类正好重载了 double 运算符,因而本行就等价于:

double n = 2 + c.operator double();

posted @   D-booker  阅读(183)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示
CONTENTS