1. 什么是运算符重载?为什么要使用运算符重载?如何进行运算符重载,举例说明。
运算符重载: 对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。
原因:
C++语言预定义的运算符只适用于基本数据类型。为了解决一些实际问题,程序员经常会定义一些新类型,即自定义类型,然而C++不允许生成新的运算符,因此为了实现对自定义类型的操作,就必须自己来编写函数说明某个运算符如何作用于这些数据类型,这样的程序可读性较差。针对这种情况,C++允许重载现有的大多数运算符,也就是允许给已有的运算符赋予新的含义,从而提高了C++的可扩展性,使得针对同样的操作,使用重载运算符比使用显式函数调用更能提高程序的可读性。以复数举例,可采用成员函数的方式或者友元函数的方式实现对运算符重载,具体实现略
class Complex{
public:
Complex(double r=0,double i=0)
{
real=r;
image=i;
}
~Complex()
{
}
double get_real();
double get_image();
friend Complex operator+(Complex &C1,Complex &C2);//友元+
friend Complex operator*(Complex &C1,Complex &C2);//友元*
Complex operator-(Complex &C1);//成员函数-
Complex operator/(Complex &C1);//成员函数/
friend istream& operator>>(istream&in,Complex&c);//输入
friend ostream& operator<<(ostream&out,Complex&c);//输出
Complex operator=(const Complex &C1);//赋值
friend int operator==(Complex &C1,Complex &C2);//相等
friend int operator!=(Complex &C1,Complex &C2);//不等
void display();
private:
double real;
double image;
};
2. 为什么重载为全局函数的运算符通常要比重载为成员函数的运算符多一个参数?举例说明。
- 当重载为成员函数时,会有一个$this$指针,指向当前的类,所以只需要一个参数就可以了。
- 当重载为全局函数时,将没有隐含的参数$this$指针,这样将会多一个参数。
Complex operator +(Complex&);
friend Complex operator+(Complex &c1,Complex &c2);
3. 什么是C++中的三大函数(The Big Three)?
见$OOP7$面向对象概论问题$10$,此处为了方便将其复制过来
- 析构函数:
~S() - 拷贝构造函数:
S(const S& s) - 赋值函数:
operator=