C++面向对象程序设计 - 运算符重载

时间:2024-04-27 07:07:05

        函数重载就是对一个已有的函数赋予新的含义,使之实现新的功能。因此一个函数名就可以用来代表不同功能的函数,也就是一名多用。运算符也可以重载,即运算符重载(operator overloading)。

一、运算符重载的方法

        运算符重载的方法是定义一个重载运算符的函数,在需要执行被重载的运算符时,系统就自动调用该函数,以实现相应的运算。运算符重载实质上是函数的重载。

        重载运算符的函数一般格式如下:

函数类型  operator 运算符名称(形参表列){

        对运算符的重载处理

}

        这里通过 + 运算符进行两个复数相加,示例代码如下:

#include <iostream>
using namespace std;
class Complex{
	public:
		Complex(){
			real = 0; imag = 0;
		}
		Complex(double r, double i){
			real = r; imag = i;
		}
		Complex operator +(Complex &c2);	// 声明重载运算符 + 的函数
		void display();
	private:
		double real;
		double imag;
};
// 定义重载运算符 + 的函数
Complex Complex::operator +(Complex &c2){
	Complex c;
	c.real = real + c2.real;		// 两上复数的实部相加
	c.imag = imag + c2.imag;		// 两个复数的虚部相加
	return c;
}
void Complex::display(){
	cout <<"("<<real<<","<<imag<<"i)"<<endl;
}
int main(){
	Complex c1(3, 4), c2(5, -10), c3;
	c3 = c1 + c2;			// 运算符 + 用于复数运算
	cout <<"c1=";c1.display();
	cout <<"c2=";c2.display();
	cout <<"c1+c2=";c3.display();
	return 0;
}

运行结果如下:

        对于上述示例的运算符重载函数 operator + 还可以改写得更简练一些,代码如下:

#include <iostream>
using namespace std;
class Complex{
	public:
		Complex(){
			real = 0; imag = 0;
		}
		Complex(double r, double i){
			real = r; imag = i;
		}
		Complex operator +(Complex &c2);	// 声明重载运算符 + 的函数
		void display();
	private:
		double real;
		double imag;
};
// 定义重载运算符 + 的函数
Complex Complex::operator +(Complex &c2){
	return Complex(real + c2.real, imag + c2.imag);
}
void Complex::display(){
	cout <<"("<<real<<","<<imag<<"i)"<<endl;
}
int main(){
	Complex c1(3, 4), c2(5, -10), c3;
	c3 = c1 + c2;			// 运算符 + 用于复数运算
	cout <<"c1=";c1.display();
	cout <<"c2=";c2.display();
	cout <<"c1+c2=";c3.display();
	return 0;
}

        return语句中的Complex(real + c2.real, imag + c2.imag) 是建立一个临时对象,它是一个无名对象,在建立临时对象过程中调用构造函数,return语句将此临时对象作为函数返回值。

二、重载运算符的规则

        1)C++不允许用户自己定义新的运算符,只能对已有的C++运算符进行重载。

        2)C++中绝大部分的运算符允许重载。如下表

双目算术运算符 +(加),-(减),*(乘),/(除),%(取模)
关系运算符 ==(等于),!=(不等于),<(小于),>(大于),<=(小于等于),>=(大于等于)
逻辑运算符 ||(逻辑或),&&(逻辑与),!(逻辑非)
单目运算符 +(正),-(负),*(指针),&(取地址)
自增自减运算符 ++(自增),--(自减)
位运算符 !(按位或),&(按位与),~(按位取反),^(按位异或),<<(左移),>>(右移)
赋值运算符 =,+=,-=,*=,/=,%=,&=,!=,^=,<<=,>>=
空间申请与释放 new,delete,new[],delete[]
其他运算符 ()(函数调用),->(成员访问),->*(成员指针访问),,(逗号),[](下标)

        不能重载的运算符:

. 成员访问运算符
.* 成员指针访问运算符
:: 域运算符
sizeof 长度运算符
?: 条件运算符

        3)重载不能改变运算符运算对象(即操作数)的个数;例如 + 运算符有两个操作数(a + b),不能重载它使用得它只有一个操作数或三个操作数。

        4)重载不能改变运算符的优先级别。重载不能改变运算符的结合性;例如 * 和 / 优先于 + 和 - ,不论怎样进行重载,各大运算符的优先级别不会改变。

        5)重载不能改变运算符的结合性。结合性决定了当多个相同优先级的运算符出现在同一个表达式中时,应该如何分组。例如 + 和 * 都是左结合的,这意味着 a + b + c会被解释为 (a + b) + c,而不是 a + (b + c)。重载运算符不能改变这种结合性。

        6)重载运算符的函数不能有默认的参数,这是因为默认参数会改变运算符的语义,导致代码的混淆和不可预测的行为。

        7)重载的运算符必须和用户定义的自定义类型的对象一起使用,其参数至少应有一个类对象(或类对象的引用)。重载运算符的目的是为了增强自定义类型的操作能力,而不是改变内置类型的行为。因此,重载的运算符必须至少涉及一个自定义类型的对象。

        8)用于类对象的运算符一般必须重载,但有两个例外,运算符 = 和 & 不必用户重载。

        9)应当使重载运算符的功能类似于该运算符作用于标准类型数据时所实现的功能。

        10)运算符重载函数可以是类的成员函数,也可以是类的友元函数,还可以是既非类的成员函数也不是友元函数的普通函数。

        总之,这些规则确保了运算符重载的一致性和可预测性,同时也避免了可能的混淆和错误。

三、运算符重载函数作为类成员函数和友元函数

        运算符重载函数除了可以作为类的成员函数,还可以是非成员函数。此时将运算符“+”重载为适用于复数相加,重载函数不作为成员函数,而放在类外作为Complex类的友函数。代码如下:

#include <iostream>
using namespace std;
class Complex{
	public:
		Complex(){
			real = 0; imag = 0;
		}
		Complex(double r, double i){
			real = r; imag = i;
		}
        // 声明重载运算符 + 的函数
		friend Complex operator +(Complex &c1, Complex &c2);	
		void display();
	private:
		double real;
		double imag;
};
// 定义重载运算符 + 的函数
Complex operator +(Complex &c1, Complex &c2){
	return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
void Complex::display(){
	cout <<"("<<real<<","<<imag<<"i)"<<endl;
}
int main(){
	Complex c1(3, 4), c2(5, -10), c3;
	c3 = c1 + c2;			// 运算符 + 用于复数运算
	cout <<"c1=";c1.display();
	cout <<"c2=";c2.display();
	cout <<"c1+c2=";c3.display();
	return 0;
}

        运行结果如下图:

四、重载双目运算符

        双目运算符(或称二元运算符)是C++中最常用的运算符,双目运算符有两个操作数,在运算符的左右两侧,如 3 + 5, a = b,i < 10等。

        这里先给一个示例,重载运算符 > ,< ,=等,代码如下:

#include <iostream>
#include <string>
using namespace std;

class String{
	public:
		String(){
			p = NULL;
		}
		String(const char *str){
			p = str;
		}
		friend bool operator > (String &str1, String &str2);
		friend bool operator < (String &str1, String &str2);
		friend bool operator == (String &str1, String &str2);
	private:
		const char *p;
};
// 重载运算符 >
bool operator > (String &str1, String &str2){
	return strcmp(str1.p, str2.p)>0 ? true : false;
}
// 重载运算符 <
bool operator < (String &str1, String &str2){
	return strcmp(str1.p, str2.p)<0 ? true : false;
}
// 重载运算符 ==
bool operator == (String &str1, String &str2){
	return strcmp(str1.p, str2.p)==0 ? true : false;
}

int main(){
	String s1("Hello"), s2("World"), s3("Computer");
	cout <<(s1 < s2) <<endl;
	cout <<(s1 > s3) <<endl;
	cout <<(s2 == s3) <<endl;
	return 0;
}

        运算结果如下:

        需要注意的是此示例中是将字符串转换为一个char*类型, 在C++中,字符串常量是const char*类型(例如“Hello”,"World"),而将其直接赋值给char* 类型的变量会导致编译器报错【[Warning] ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]】- C++禁止针字符串常量转换为'char*'。将只读的字符串常量赋值给char*类型修改为可变的内容,这是不被允许的,所以在定义String类中的私有数据成中和构造函数中形参声明,一定要在前面另上const。

        下面将以上代码进行优化,让显示的结果更为直观些,代码如下:

#include <iostream>
#include <string>
using namespace std;

class String{
	public:
		String(){
			p = NULL;
		}
		String(const char *str){
			p = str;
		}
		friend bool operator > (String &str1, String &str2);
		friend bool operator < (String &str1, String &str2);
		friend bool operator == (String &str1, String &str2);
		friend void compare(String &str1, String &str2);
		void display(){
			cout <<p;
		}
	private:
		const char *p;
};
// 重载运算符 >
bool operator > (String &str1, String &str2){
	return strcmp(str1.p, str2.p)>0 ? true : false;
}
// 重载运算符 <
bool operator < (String &str1, String &str2){
	return strcmp(str1.p, str2.p)<0 ? true : false;
}
// 重载运算符 ==
bool operator == (String &str1, String &str2){
	return strcmp(str1.p, str2.p)==0 ? true : false;
}
// 更直观显示结果
void compare(String &str1, String &str2){
	if(operator > (str1, str2) == 1){
		cout <<str1.p <<'>' <<str2.p;
	} else{
		if(operator < (str1, str2) == 1){
			cout <<str1.p <<'<' <<str2.p;
		} else if(operator == (str1, str2) == 1){
			cout <<str1.p <<'=' <<str2.p;
		}
	}
	cout <<endl;
}

int main(){
	String s1("Hello"), s2("World"), s3("Computer");
	compare(s1, s2);
	compare(s1, s3);
	compare(s2, s3);
	return 0;
}

        运行结果如下:

        此时需要区分下strcmp 和 operator >,在c++中strcp是C标准库的函数,用于比较两个字符中(即char*指针向的字符串);而operator >是一个运算符重载,可以在自定义的类中定义,用于比较对象。

        strcmp函数返回一个整数,表示两上字符串的字典关系:

  • 如果返回值小于0,表示值1指向的字符串在字典上小于值2指向的字符串。
  • 如果返回值等于0,表示两个字符串相等。
  • 如果返回值大于0,表示值1指向的字符串在字典上大于值2指向的字符串。

        示例中operator > 或 operator < 或 operator == 是String类中声明的3个重载函数为友元函数,并在类外分别定义了3个运算符重载函数。C++编译系统将程序中的表达式 s1 > s2 解释为 operator > (s1, s2),所以上例代码中写法也就不难理解了。将compare函数也可以改为以下形式,代码如下:

void compare(String &str1, String &str2){
	if((str1 > str2) == 1){
		cout <<str1.p <<'>' <<str2.p;
	} else{
		if((str1 < str2) == 1){
			cout <<str1.p <<'<' <<str2.p;
		} else if((str1 == str2) == 1){
			cout <<str1.p <<'=' <<str2.p;
		}
	}
	cout <<endl;
}

五、重载单目运算符

        单目运算符只有一上操作数,如 !a,-b,&c,*p,还有常用的 ++i 和--i等。重载单目运算符的方法与重载双目运算符的方法类似的。但由于单目运算符只有一个操作数,因此运算符重载函数只有一个参数,如果运算符重载函数作为成员函数,则还可以省略此参数。

        这里通过一个计算器Timer类来演示一下单目运算符的重载,代码如下:

#include <iostream>
using namespace std;
class Timer{
	public:
		Timer(){
			hour = 0;
			minute = 0;
			second = 0;
		}
		Timer(int h, int m, int s): hour(h), minute(m), second(s){}
		Timer operator ++ ();		// 声明运算符重载
		// 定义输出时间函数
		void display(){
			cout <<hour <<":" <<minute <<":" <<second <<endl;
		}
	private:
		int hour;
		int minute;
		int second;
};
Timer Timer::operator ++(){
	// 分钟 满60秒进1分钟
	if(++second>=60) {
		second -= 60;
		++minute;
	}
	// 小时 满60分钟进1小时
	if(minute>=60){
		minute -= 60;
		++hour;
	}
	// 返回当前对象
	return *this;
}
int main(){
	Timer t1(1, 20, 0);
	for(int i = 0; i < 61; i++){
		++t1;
		t1.display();
	}
	return 0;
}

        运行一共输出61行,结果如下:

1:20:1
1:20:2
1:20:3
1:20:4
1:20:5
1:20:6

......
1:20:56
1:20:57
1:20:58
1:20:59
1:21:0
1:21:1

       在C++中,如果在自增(自减)运算符重载函数中,增加一个int型形参,就是后后置自增(自减)运算符函数。示例如下:

#include <iostream>
using namespace std;
class Timer{
	public:
		Timer(){
			hour = 0;
			minute = 0;
			second = 0;
		}
		Timer(int h, int m, int s): hour(h), minute(m), second(s){}
		Timer operator ++ ();		// 声明前置自增运算符重载函数
		Timer operator ++ (int);	//声明后置自增运算符重载函数
		// 定义输出时间函数
		void display(){
			cout <<hour <<":" <<minute <<":" <<second <<endl;
		}
	private:
		int hour;
		int minute;
		int second;
};
// 定义前置自增运算符重载函数
Timer Timer::operator ++(){
	// 分钟 满60秒进1分钟
	if(++second>=60) {
		second -= 60;
		++minute;
	}
	// 小时 满60分钟进1小时
	if(minute>=60){
		minute -= 60;
		++hour;
	}
	// 返回当前对象
	return *this;
}
// 定义后置自增运算符重载函数
Timer Timer::operator ++(int){
	// 分钟 满60秒进1分钟
	if(++second>=60) {
		second -= 60;
		++minute;
	}
	// 小时 满60分钟进1小时
	if(minute>=60){
		minute -= 60;
		++hour;
	}
	// 返回当前对象
	return *this;
}
int main(){
	Timer t1(1, 20, 0), t2(3, 10, 20);
	for(int i = 0; i < 61; i++){
		++t1;
		t1.display();
	}
	cout <<endl;
	for(int i = 0; i < 61; i++){
		t2++;
		t2.display();
	}
	return 0;
}

        运行结果如下:

// 前置结果

1:20:1
1:20:2
1:20:3
1:20:4
1:20:5
1:20:6
.......
1:20:56
1:20:57
1:20:58
1:20:59
1:21:0
1:21:1

// 后置结果

3:10:21
3:10:22
3:10:23
3:10:24
3:10:25
3:10:26
.......
3:11:17
3:11:18
3:11:19
3:11:20
3:11:21

        注意的时,如果Timer类中未声明和定义后置自增运算符重载,则系统编译时会报错【[Error] no 'operator++(int)' declared for postfix '++' [-fpermissive]】- 没有为后缀‘++’声明'operator++(int)'。

        "++"或"--"前置和后置的区别:前置是先自加,返回是修改后的对象本身;后置是返回自加前的对象,然后对象再自加。

六、重载流插入运算符和提取运算符

        C++的插入运算符“<<”和流提取运算符“>>”是C++在类库中提供的,所有C++编译系统都在类库中提供输入流类istream和输出流类otream。cin和cout分别是istream和ostream类的对象。在类库提供的头文件中已经对"<<"和">>"进行了重载,使之作为流插入运算符和流提取运算符,能用来输出和输入C++标准类型的数据。

        对"<<"和">>"重载的函数形式如下:

istream & operator >> (istream &, 自定义类 &);

ostream & operator << (ostream &, 自定义类 &);

        第一个参数必须是流类型引用,第二个参数是要进行操作的类,所以重载"<<"和">>"的函数作为友函数或普通的函数,而不能将它们定义为成员函数。

        这是因为作为成员函数,这些运算符只能访问一个对象(即该成员函数所属的类的实例),然而在流操作中,我们需要同时访问流对象和用户定义的对象。如果试图将 << 和 >> 作为成员函数重载,那么它只能访问到自定义的对象,而无法访问到流对象,这显示是无法满足需求的。

        通过将 << 和 >> 重载为非成员函数,可以让它们同时接受一个流对象和一个自定义的对象作为参数,这样就可以在函数中同时访问和操作这两个对象。此外,为了允许这些非成员函数访问类的私有或保护成员,通常需要将这些函数声明为类的友元函数。

        这里将在“一”、“二”中的基础上,用重载的">>"输入数值,"<<"输出复数,代码如下:

#include <iostream>
using namespace std;
class Complex{
	public:
		Complex(){
			real = 0; imag = 0;
		}
		Complex(double r, double i){
			real = r; imag = i;
		}
		Complex operator +(Complex &c2);	// 声明重载运算符 + 的函数
		friend ostream& operator <<(ostream&, Complex&);
		friend istream& operator >>(istream&, Complex&);
	private:
		double real;
		double imag;
};
// 定义重载运算符 + 的函数
Complex Complex::operator +(Complex &c2){
	return Complex(real + c2.real, imag + c2.imag);
}
// 定义运算符">>"重载函数
istream& operator >>(istream& input, Complex& c){
	cout <<"Please enter the value:" <<endl;
	input >>c.real >>c.imag;
	return input;
}
// 定义运算符"<<"重载函数
ostream& operator <<(ostream& output, Complex& c){
	cout <<"("<<c.real<<","<<c.imag<<"i)"<<endl; 
	return output;
}
int main(){
	Complex c1, c2, c3;
	cin >>c1 >>c2;
	c3 = c1 + c2;			// 运算符 + 用于复数运算
	cout <<endl;
	cout <<"c1=" <<c1;
	cout <<"c2=" <<c2;
	cout <<"c1+c2=" <<c3;
	return 0;
}

        运行后则会按运算符">>"重载后格式输入,以及运算符"<<"重载后格式输出,结果如下图:

        在C++中,运算符重载是很重要的、很有实用意义的,它使类的设计更加丰富多彩,扩大了类的功能和使用范围,使程序易于理解,易于对对象进行操作,它体现了为用户着想、方便用户使用的思路。

        也能体现到运算符重载中使用引用(reference)的重要性,利用引用作为函数形参可以不生成临时变量,减少了时间和空间的开销,通过传址的方式使形参成为实参的别名,调用过程中不是用传递值的方式 进行虚实结合。