第三章 操作符重载
复数:3+4i
Complex
c1 - (c2 + c3)
c1.sub (c2.add (c3))
一、操作符标记和操作符函数
1.双目操作符:L#R
成员函数形式:L.operator# ®
左调右参
全局函数形式:::operator# (L, R)
左一右二
2.单目操作符:#O/O#
成员函数形式:O.operator# ()
全局函数形式:::operator# (O)
3.三目操作符:不考虑
二、双目操作符
1. +/-/*//
操作数在计算前后不变。
表达式的值是右值。
例子:
#include <iostream> //操作符重载
using namespace std;
class Complex {
public:
Complex (int r = 0, int i = 0) :
m_r (r), m_i (i) {}
void print (void) const {
cout << m_r << '+' << m_i << 'i' << endl;
}
// 第一个const:返回右值,返回的对象不能接受赋值。
// 第二个const:支持常量型右操作数,可以接受有常属性的变量为参数,将引用声明为常引用才能指向常变量,常引用也可以指向非常变量。
// 第三个const:支持常量型左操作数,使this指针变为常指针,也可以指向有常属性的变量。
const Complex operator+ (const Complex& r) const { //操作符重载的成员函数形式:L.operator+(R)
return Complex (m_r + r.m_r, m_i + r.m_i);
}
private:
int m_r;
int m_i;
friend const Complex operator- (const Complex&,
const Complex&); //将该函数声明为友远这样该函数就可以访问类的私有部分
};
const Complex operator- (const Complex& l,const Complex& r) { //操作符重载的全局函数形式,::operator-(L,R)
return Complex (l.m_r - r.m_r, l.m_i - r.m_i);
}
int main (void) {
const Complex c1 (1, 2);
c1.print ();
const Complex c2 (3, 4);
Complex c3 = c1 + c2; // c3 = c1.operator+ (c2)
c3.print (); // 4+6i
// (c1 + c2) = c3;
c3 = c2 - c1; // c3 = ::operator- (c2, c1)
c3.print (); // 2+2i
return 0;
}
2. +=/-=/*=…
左变右不变。
表达式的值是左值,左操作数的引用。
(a += b) = c;
例子:
#include <iostream>
using namespace std;
class Complex {
public:
Complex (int r = 0, int i = 0) :
m_r (r), m_i (i) {}
void print (void) const {
cout << m_r << '+' << m_i << 'i' << endl;
}
//成员函数形式:
Complex& operator+= (const Complex& r) { //返回的是左操作数的引用,是可以赋值的,所以最前面不加const,调用该函数的左操作数是要改变的也就是this会修改,也就是调用函数的参数被修改,所以{前也不加const。
m_r += r.m_r;
m_i += r.m_i;
return *this;//返回该调用操作数
}
//全局函数形式:(把定义与声明合二为一,因为有friend,所以是全局函数)
friend Complex& operator-= (Complex& l,
const Complex& r) { //第一个参数l为左操作数引用,可被修改,所以不加const,而第二个参数r为右操作数,值不会被修改,所以加const。
l.m_r -= r.m_r;
l.m_i -= r.m_i;
return l;//返回左操作数
}
private:
int m_r;
int m_i;
};
int main (void) {
Complex c1 (1, 2), c2 (3, 4);
c1 += c2; // c1.operator+= (c2)
c1.print (); // 4+6i
Complex c3 (5, 6);
(c1 += c2) = c3;//返回的是左操作数c1的引用,把c3赋值给c1.
c1.print (); // 5+6i
c1 -= c2; // ::operator-= (c1, c2)
c1.print (); // 2+2i
(c1 -= c2) = c3;
c1.print (); // 5+6i;
return 0;
}
3. <</>>
int i = 10;
float f = 1.23;
Complex c (…);
cout << c << i << f << endl;
cin >> c;
左操作数ostream/istream类型,不能是常量,不能拷贝。
右操作数自定义类型,对于<<可以是常量,对于>>不能是常量。
表达式的值是左操作数的引用。
::operator<< (cout, c).operator<< (i).operator<< (f).operator<< (endl);
例子:
#include <iostream>
//输入与输出。
using namespace std;
class Complex {
public:
Complex (int r = 0, int i = 0) :
m_r (r), m_i (i) {}
void print (void) const {
cout << m_r << '+' << m_i << 'i' << endl;
}
//全都使用全局函数的形式
friend ostream& operator<< (ostream& os, //返回的是左操作数的引用
const Complex& r) { //因为右操作数是要输出的,所以右操作数可以是常量,所以声明为常引用,加const,也可做非常变量的引用。
return os << r.m_r << '+' << r.m_i << 'i';//返回左操作数的引用
}
friend istream& operator>> (istream& is,//返回的是左操作数的引用
Complex& r) { //因为右操作数是要输入的,所以右操作数不能是常量,不加const
return is >> r.m_r >> r.m_i; //返回左操作数的引用
}
private:
int m_r;
int m_i;
};
int main (void) {
Complex c1 (1, 2), c2 (3, 4);
cout << c1 << endl << c2 << endl;
// ::operator<<(::operator<<(cout,c1).operator<<(
// endl),c2).operator<<(endl);
cin >> c1 >> c2;
cout << c1 << endl << c2 << endl;
return 0;
}
三、单目操作符
1.-(取负)/!/~
操作数不变。
表达式的值是右值。
例子:
#include <iostream>
using namespace std;
class Complex {
public:
Complex (int r = 0, int i = 0) :
m_r (r), m_i (i) {}
void print (void) const {
cout << m_r << '+' << m_i << 'i' << endl;
}
//成员函数形式:
const Complex operator- (void) const { //只有一个操作数,且作为调用参数,所以没有形参。因为返回的是右值,是常量,所以要加const(第一个const)。操作数不改变,就是this不可改变,也加const(第二个const)。
return Complex (-m_r, -m_i);//返回的是右值(常数)
}
//全局函数形式:
friend const Complex operator~ (
const Complex& o) { //就一个操作数,且不改变,加const
return Complex (o.m_i, o.m_r);//交换实部与虚部
}
private:
int m_r;
int m_i;
};
int main (void) {
const Complex c1 (1, 2);
Complex c2 = -c1; // c2=c1.operator-()
c2.print (); // -1+-2i
Complex c3 = ~c1; // c3=::operator~(c1)
c3.print (); // 2+1i;
return 0;
}
2.前++/前–
操作数变。
表达式的值是运算以后的值。
表达式的值是左值,操作数的引用。
(++i) = 100;
++++++i;
例子:
#include <iostream>
using namespace std;
class Complex {
public:
Complex (int r = 0, int i = 0) :
m_r (r), m_i (i) {}
void print (void) const {
cout << m_r << '+' << m_i << 'i' << endl;
}
//成员函数形式:
Complex& operator++ (void) { //只有一个操作数,且该操作数是改变的,所以前{不加const。而返回的是一个可以改变的左值,既操作数的引用,所以可以改变,最前面不加const。
++m_r;
++m_i;
return *this;
}
//全局函数形式:
friend Complex& operator-- (Complex& o) { //返回的是操作数本身,既引用。
--o.m_r;
--o.m_i;
return o; //返回操作数的引用。
}
private:
int m_r;
int m_i;
};
int main (void) {
Complex c1 (1, 2);
Complex c2 = ++c1; // c2=c1.operator++() //成员函数形式
c1.print (); // 2+3i
c2.print (); // 2+3i
(++c1) = Complex (10, 20);
c1.print (); // 10+20i;
(++++++c1).print (); // 13+23i
c2 = --c1; // c2=::operator--(c1) //全局函数形式
c1.print (); // 12+22i
c2.print (); // 12+22i
return 0;
}
3.后++/后–
操作数变。
表达式的值是运算以前的值。
表达式的值是右值。
例子:
#include <iostream>
using namespace std;
class Complex {
public:
Complex (int r = 0, int i = 0) :
m_r (r), m_i (i) {}
void print (void) const {
cout << m_r << '+' << m_i << 'i' << endl;
}
const Complex operator++ (int) { //返回的是一个右值,不变,所以最前面家一个const。int是哑元,占个位置,没有实际意义,与有形参的进行匹配。
Complex old (*this);
++m_r;
++m_i;
return old;
}
friend const Complex operator--(Complex& o, int) { //操作数会被修改,所以用引用,不加const。Int是占位置的,没有实际意义
Complex old (o);
--o.m_r;
--o.m_i;
return old;
}
private:
int m_r;
int m_i;
};
int main (void) {
Complex c1 (1, 2);
Complex c2 = c1++; // c2=c1.operator++(0) //成员函数形式
c1.print (); // 2+3i;
c2.print (); // 1+2i;
// (c1++) = c2;
// c1++++++;
c2 = c1--; // c2=::operator--(c1,0) //全局函数形式
c1.print (); // 1+2i //c1进行了--,得到新的值。
c2.print (); // 2+3i //c2得到表达式之前的值。
return 0;
}
四、其它操作符
1.下标操作符:[]
int arr[10] = { ... };
arr[1] = 10;
cout << arr[1] << endl;
-----------------------
class Array { ... };
Array arr (...);
arr[1] = 10;
cout << arr[1] << endl;
双目操作符,左操作数是一个具有容器特性的对象,右操作数是容器中特定数据元素的索引(基零的下标)。
下标表达式的值可以是左值,也可以是右值,由容器对象的常属性决定。常容器下标表达式的值是右值,非常容器下标表达式的值是左值。
例子:
#include <iostream>
using namespace std;
class Array {
public:
Array (size_t size = 1) : //构造函数
m_data (new int[size]) {}
~Array (void) { //析构函数
if (m_data) {
delete m_data;
m_data = NULL;
}
}
int& operator[] (size_t i) { //不带有常属性的容器对象,没有常属性,所以最前面不加const,返回的是一个引用,可以修改,所以{前不加const
return m_data[i]; //返回类型为该数组中第i个元素的引用
}
const int& operator[] (size_t i) const { //带有常属性的容器对象。是个常量,所以最前面加const,因为返回的是一个不可修改的右值,所以加了第二个const。
return const_cast<Array&> (*this)[i]; //去常,转换成不具有常属性,可以调用上面那个重载。
}
private:
int* m_data;
};
int main (void) {
Array arr (10);//不具有常属性
for (size_t i = 0; i < 10; ++i)
arr[i] = i; // arr.operator[](i) = i;
arr[0]++;//没有常属性,可以修改
const Array& cr = arr;//具有常属性
for (size_t i = 0; i < 10; ++i)
cout << cr[i] << ' ';
cout << endl;
// cr[0]++; //具有常属性,不可修改,所以报错。
return 0;
}
2.函数操作符:()
如果为一个类定义了形如:
返回类型 operator() (形参表) {…}
的操作符函数,那么这个类所实例化的对象就可以被当做函数使用。
例子:
include <iostream>
using namespace std;
class Square {
public:
double operator() (double x) {
return x * x;
}
};
class Integer {
public:
explicit Integer (int i = 0) : m_i (i) {} //explicit强制要求用这个构造函数进行类型转换时必须要用显式类型转换
void print (void) const {
cout << m_i << endl;
}
Integer& operator() (int i) {
m_i += i;
return *this;//返回自引
}
Integer& operator, (int i) {
m_i += i;
return *this;
}
operator int (void) const { //可以将Integer转换为int
return m_i;
}
private:
int m_i;
};
void foo (const Integer& i) {
i.print ();
}
Integer bar (void) {
return Integer (300);//因为返回的是Integer,所以将300转换为Integer类型的
}
int main (void) {
Square square;
cout << square (3) << endl;//这个类的对象可以直接当函数使用。输出为“9”
// cout << square.operator() (3) << endl;
Integer i (10);
i (1) (2) (3) (17);//10+1+2+3+17
i.print (); // 33
i, 1, 2, 3, 17; //33+1+2+3+17
i.print (); // 56
i = (Integer)100;//i是Integer类型的,所以要将100进行转换
i.print ();
foo (static_cast<Integer> (200));//静态类型转换
bar ().print ();
int n = i;
cout << n << endl;
return 0;
}
3.解引用(*)和间接访问(->)操作符
以指针的方式使用类类型的对象。
例子:
#include <iostream>
#include <memory>
using namespace std;
class A {
public:
A (void) {
cout << "构造" << endl;
}
~A (void) {
cout << "析构" << endl;
}
void hello (void) {
cout << "Hello, World !" << endl;
}
};
class PA {
public:
PA (A* p = NULL) : m_p (p) {}
~PA (void) { //智能指针,在栈内的mp消灭时,同时将它所指向的堆中的内存释放(delete)
if (m_p) {
delete m_p;
m_p = NULL;
}
}
A& operator* (void) const { //返回引用
return *m_p;
}
A* operator-> (void) const { //返回指针,既地址
// return &**this; //调用上面的重载函数
return m_p; //返回的只是一个地址
}
PA (PA& that) : m_p (that.release ()) {}//拷贝构造函数,将自己指向NULL,并将自己指向的内存返回
PA& operator= (PA& that) {
if (&that != this)
reset (that.release ());//reset的参数为that所返回的内存地址
return *this;
}
private:
A* release (void) {
A* p = m_p;//先将内存保存下来
m_p = NULL;//
return p;
}
void reset (A* p) {
if (p != m_p) {
delete m_p;
m_p = p;
}
}
A* m_p;
};
void bar (auto_ptr<A> pa) {
cout << "bar:";
pa -> hello ();
}
void foo (void) {
PA pa (new A);//PA保存分配的内存的地址,当在栈中的PA销毁时,调用PA的析构函数,自动执行其中的代码将其delete把内存释放,是智能指针
// A* pa = new A;
// pa -> hello ();
// (*pa).hello ();
// A* pb = pa;
pa -> hello (); // pa.operator->()->hello();//pa返回的只是一个地址,所以用“->”
(*pa).hello (); // pa.operator*().hello(); //(*pa)返回的是引用,所以可以用“.”访问
PA pb = pa;//如果没有自己写的拷贝赋值函数,则会出现浅拷贝,出现double free,因为有两个指针都指向同一个内存地址,所以会执行两次析构函数,会出问题。
//上面自己写的拷贝构造函数,使得pa指向NULL,并返回自己指向的内存地址
//然后调用操作符重载函数(“=”的),先看pa指向的内存与执行拷贝构造所返回的内存(pb原先指向的内存)是否相同,不相同,则将pb所指向的内存释放,再使pb指向pa原先指向的内存
pb -> hello ();
auto_ptr<A> pa1 (new A);//auto_ptr只能用于单个变量,不能用于数组,但smart_ptr都可以
pa1 -> hello ();
auto_ptr<A> pa2 = pa1;
(*pa2).hello ();
bar (pa2);//实参与bar函数中的形参类似与(PA pb=pa),执行后,pa2就指向了NULL,用不了了,gai内存的析构有bar函数中的形参来实现
cout << pa2.get () << endl;
}
// smart_ptr
int main (void) {
foo ();
return 0;
}
4.自定义类型转换和类型转换操作符
1)通过单参构造实现自定义类型转换
如果A类中有一个可以接受B类对象做为唯一参数的构造函数,那么B类型的对象就可以根据该构造函数被转换为A类型。
通过explicit关键字,可以强制使用该构造函数所完成的类型转换必须显示进行。
2)通过类型转换操作符函数实现自定义类型转换
如果A类中有一个形如
operator B (void) const { … }
的操作符函数,那么A类型的对象就可以根据该函数被转换为B类型。
3)如果目标类型是类类型,源类型是基本类型,那么就只能通过在目标类型中定义以源类型为单参的构造函数实现类型转换。
如果目标类型是基本类型,源类型是类类型,那么就只能通过在源类型中定义以目标类型为函数名的类型转换操作符函数实现类型转换。
如果目标类型和源类型都是类类型,那么以上两种方法任取其一,但是不能同时使用。
如果目标类型和源类型都是基本类型,那么无法实现自定义类型转换。
例子:
#include <iostream>
using namespace std;
class Square {
public:
double operator() (double x) {
return x * x;
}
};
class Integer {
public:
explicit Integer (int i = 0) : m_i (i) {} //explicit强制要求用这个构造函数进行类型转换时必须要用显式类型转换
void print (void) const {
cout << m_i << endl;
}
Integer& operator() (int i) {
m_i += i;
return *this;//返回自引
}
Integer& operator, (int i) {
m_i += i;
return *this;
}
operator int (void) const { //可以将Integer转换为int
return m_i;
}
private:
int m_i;
};
void foo (const Integer& i) {
i.print ();
}
Integer bar (void) {
return Integer (300);//因为返回的是Integer,所以将300转换为Integer类型的
}
int main (void) {
Square square;
cout << square (3) << endl;//这个类的对象可以直接当函数使用。输出为“9”
// cout << square.operator() (3) << endl;
Integer i (10);
i (1) (2) (3) (17);//10+1+2+3+17
i.print (); // 33
i, 1, 2, 3, 17; //33+1+2+3+17
i.print (); // 56
i = (Integer)100;//i是Integer类型的,所以要将100进行转换
i.print ();
foo (static_cast<Integer> (200));//静态类型转换
bar ().print ();
int n = i;
cout << n << endl;
return 0;
}
5.new/delete操作符
例子:
#include <iostream>
#include <cstdlib>
using namespace std;
class A {
public:
~A (void) {}//析构函数
static void* operator new (size_t size) { // size_t等于unsigned int,但是一般要用size_t。
void* p = malloc (size); //这是调用构造函数,创建对象
cout << "我的new :" << p << ' '
<< size << endl;
return p; //完成内存分配,返回分配好的内存地址
}
static void operator delete (void* p) {
cout << "我的delete:" << p << endl;
free (p); //完成内存释放
}
static void* operator new[] (size_t size) {
void* p = malloc (size); //这时调用构造函数,创建对象
cout << "我的new[] :" << p << ' '<< size << endl;
//打印出分配的内存地址
return p; //完成内存分配,返回分配好的内存地址
}
static void operator delete[] (void* p) {
cout << "我的delete[]:" << p << endl;
free (p); //完成内存释放
}
private:
int m_i;
double m_d;
char m_c;
}; // IIIIDDDDDDDDCXXX sizeof(A)为16
int main (void) {
cout << sizeof (A) << endl;//16
A* pa = new A; //我的new:0x85bd008 16
cout << pa << endl;//0x86bd008
delete pa; //我的delete:0x85bd008
pa = new A[2]; //我的new[]:0x9fc2008 32
cout << pa << endl;//0x8fc2008
delete[] pa; //我的delete[]:0x9fc2008
//delete pa //会崩溃,错误,因为delete的地址与new[]的地址不相同,会偏移四个字节,造成局部释放
return 0;
}
五、关于操作符重载的限制
1.至少有一个操作数是类类型的。
int a = 10, b = 20;
int c = a + b; // 200
int operator+ (int a, int b) {
return a * b;
} // ERROR !
2.不是所有的操作符都能重载。
:: - 作用域限定
. - 直接成员访问
.* - 直接成员指针解引用
?: - 三目运算符
sizeof - 获取字节数
typeid - 获取类型信息
3.不是所有的操作符都可以用全局函数的方式实现。
= - 拷贝赋值
[] - 下标
() - 函数
-> - 间接成员访问
4.不能发明新的操作符,不能改变操作数的个数
x ** y; // x^y
@