C++运算符重载

本文详细介绍了C++中运算符重载的概念、作用及限制,包括重载的形式、适用的运算符种类,以及如何实现复数类的四则运算等案例。

运算符重载的几个问题

  1. 运算符重载的作用是什么?

  它答应你为类的用户提供一个直觉的接口。

  运算符重载答应C/C++的运算符在用户定义类型(类)上拥有一个用户定义的意义。重载的运算符是函数调用的语法修饰:

class Fred
{
public:
// ...
};

#if 0
// 没有算符重载:
Fred add(Fred, Fred);
Fred mul(Fred, Fred);

Fred f(Fred a, Fred b, Fred c)
{
return add(add(mul(a,b), mul(b,c)), mul(c,a)); // 哈哈,多可笑...
}
#else
// 有算符重载:
Fred operator+ (Fred, Fred);
Fred operator* (Fred, Fred);

Fred f(Fred a, Fred b, Fred c)
{
return a*b + b*c + c*a;
}
#endif
  2. 算符重载的好处是什么?

  通过重载类上的标准算符,你可以发掘类的用户的直觉。使得用户程序所用的语言是面向问题的,而不是面向机器的。

  最终目标是降低学习曲线并减少错误率。

  3. 哪些运算符可以用作重载?

  几乎所有的运算符都可用作重载。具体包含:

  算术运算符:+,-,*,/,%,++,--;
  位操作运算符:&,,~,^,<<,>>
  逻辑运算符:!,&&,;
  比较运算符:<,>,>=,<=,==,!=;
  赋值运算符:=,+=,-=,*=,/=,%=,&=,=,^=,<<=,>>=;
  其他运算符:[],(),->,,(逗号运算符),new,delete,new[],delete[],->*。

  下列运算符不答应重载:

  .,.*,::,?:

  4. 运算符重载后,优先级和结合性怎么办?

  用户重载新定义运算符,不改变原运算符的优先级和结合性。这就是说,对运算符重载不改变运算符的优先级和结合性,并且运算符重载后,也不改变运算符的语法结构,即单目运算符只能重载为单目运算符,双目运算符只能重载双目运算符。

  5. 编译程序如何选用哪一个运算符函数?

  运算符重载实际是一个函数,所以运算符的重载实际上是函数的重载。编译程序对运算符重载的选择,遵循着函数重载的选择原则。当碰到不很明显的运算时,编译程序将去寻找参数相匹配的运算符函数。

  6. 重载运算符有哪些限制?

  (1) 不可臆造新的运算符。必须把重载运算符限制在C++语言中已有的运算符范围内的答应重载的运算符之中。

  (2) 重载运算符坚持4个“不能改变”。

  ·不能改变运算符操作数的个数;
  ·不能改变运算符原有的优先级;
  ·不能改变运算符原有的结合性;
  ·不能改变运算符原有的语法结构。

  7. 运算符重载时必须遵循哪些原则?

  运算符重载可以使程序更加简洁,使表达式更加直观,增加可读性。但是,运算符重载使用不宜过多,否则会带来一定的麻烦。

  使用重载运算符时应遵循如下原则:

  (1) 重载运算符含义必须清楚。

  (2) 重载运算符不能有二义性。 运算符重载函数的两种形式

  运算符重载的函数一般地采用如下两种形式:成员函数形式和友元函数形式。这两种形式都可访问类中的私有成员。

  1. 重载为类的成员函数

  这里先举一个关于给复数运算重载复数的四则运算符的例子。复数由实部和虚部构造,可以定义一个复数类,然后再在类中重载复数四则运算的运算符。先看以下源代码:

#include <iostream.h>

class complex
{
public:
complex() { real=imag=0; }
complex(double r, double i)
{
real = r, imag = i;
}
complex operator +(const complex &c);
complex operator -(const complex &c);
complex operator *(const complex &c);
complex operator /(const complex &c);
friend void print(const complex &c);
private:
double real, imag;
};

inline complex complex::operator +(const complex &c)
{
return complex(real + c.real, imag + c.imag);
}

inline complex complex::operator -(const complex &c)
{
return complex(real - c.real, imag - c.imag);
}

inline complex complex::operator *(const complex &c)
{
return complex(real * c.real - imag * c.imag, real * c.imag + imag * c.real);
}

inline complex complex::operator /(const complex &c)
{
return complex((real * c.real + imag + c.imag) / (c.real * c.real + c.imag * c.imag),
(imag * c.real - real * c.imag) / (c.real * c.real + c.imag * c.imag));
}

void print(const complex &c)
{
if(c.imag<0)
cout<<c.real<<c.imag<<'i';
else
cout<<c.real<<'+'<<c.imag<<'i';
}

void main()
{
complex c1(2.0, 3.0), c2(4.0, -2.0), c3;
c3 = c1 + c2;
cout<<"/nc1+c2=";
print(c3);
c3 = c1 - c2;
cout<<"/nc1-c2=";
print(c3);
c3 = c1 * c2;
cout<<"/nc1*c2=";
print(c3);
c3 = c1 / c2;
cout<<"/nc1/c2=";
print(c3);
c3 = (c1+c2) * (c1-c2) * c2/c1;
cout<<"/n(c1+c2)*(c1-c2)*c2/c1=";
print(c3);
cout<<endl;
}
  该程序的运行结果为:


c1+c2=6+1i
c1-c2=-2+5i
c1*c2=14+8i
c1/c2=0.45+0.8i
(c1+c2)*(c1-c2)*c2/c1=9.61538+25.2308i
  在程序中,类complex定义了4个成员函数作为运算符重载函数。将运算符重载函数说明为类的成员函数格式如下:

  <类名> operator <运算符>(<参数表>)

  其中,operator是定义运算符重载函数的要害字。

  程序中出现的表达式:

  c1+c2

  编译程序将给解释为:

  c1.operator+(c2)

  其中,c1和c2是complex类的对象。operator+()是运算+的重载函数。

  该运算符重载函数仅有一个参数c2。可见,当重载为成员函数时,双目运算符仅有一个参数。对单目运算符,重载为成员函数时,不能再显式说明参数。重载为成员函数时,总时隐含了一个参数,该参数是this指针。this指针是指向调用该成员函数对象的指针。

  2. 重载为友元函数

  运算符重载函数还可以为友元函数。当重载友元函数时,将没有隐含的参数this指针。这样,对双目运算符,友元函数有2个参数,对单目运算符,友元函数有一个参数。但是,有些运行符不能重载为友元函数,它们是:=,(),[]和->。

  重载为友元函数的运算符重载函数的定义格式如下:

  friend <类型说明符> operator <运算符>(<参数表>)
  {……}

  下面用友元函数代码成员函数,重载编写上述的例子,程序如下:

#include <iostream.h>

class complex
{
public:
complex() { real=imag=0; }
complex(double r, double i)
{
real = r, imag = i;
}
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
void print(const complex &c);
private:
double real, imag;
};

complex operator +(const complex &c1, const complex &c2)
{
return complex(c1.real + c2.real, c1.imag + c2.imag);
}

complex operator -(const complex &c1, const complex &c2)
{
return complex(c1.real - c2.real, c1.imag - c2.imag);
}

complex operator *(const complex &c1, const complex &c2)
{
return complex(c1.real * c2.real - c1.imag * c2.imag, c1.real * c2.imag + c1.imag * c2.real);
}

complex operator /(const complex &c1, const complex &c2)
{
return complex((c1.real * c2.real + c1.imag + c2.imag) / (c2.real * c2.real + c2.imag * c2.imag),
(c1.imag * c2.real - c1.real * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag));
}

void print(const complex &c)
{
if(c.imag<0)
cout<<c.real<<c.imag<<'i';
else
cout<<c.real<<'+'<<c.imag<<'i';
}

void main()
{
complex c1(2.0, 3.0), c2(4.0, -2.0), c3;
c3 = c1 + c2;
cout<<"/nc1+c2=";
print(c3);
c3 = c1 - c2;
cout<<"/nc1-c2=";
print(c3);
c3 = c1 * c2;
cout<<"/nc1*c2=";
print(c3);
c3 = c1 / c2;
cout<<"/nc1/c2=";
print(c3);
c3 = (c1+c2) * (c1-c2) * c2/c1;
cout<<"/n(c1+c2)*(c1-c2)*c2/c1=";
print(c3);
cout<<endl;
}
  该程序的运行结果与上例相同。前面已讲过,对又目运算符,重载为成员函数时,仅一个参数,另一个被隐含;重载为友元函数时,有两个参数,没有隐含参数。因此,程序中出现的 c1+c2

  编译程序解释为:

  operator+(c1, c2)

  调用如下函数,进行求值,

  complex operator +(const coplex &c1, const complex &c2)
3. 两种重载形式的比较

  一般说来,单目运算符最好被重载为成员;对双目运算符最好被重载为友元函数,双目运算符重载为友元函数比重载为成员函数更方便此,但是,有的双目运算符还是重载为成员函数为好,例如,赋值运算符。因为,它假如被重载为友元函数,将会出现与赋值语义不一致的地方。 其他运算符的重载举例

  1).下标运算符重载

  由于C语言的数组中并没有保存其大小,因此,不能对数组元素进行存取范围的检查,无法保证给数组动态赋值不会越界。利用C++的类可以定义一种更安全、功能强的数组类型。为此,为该类定义重载运算符[]。

  下面先看看一个例子:

#include <iostream.h>

class CharArray
{
public:
CharArray(int l)
{
Length = l;
Buff = new char[Length];
}
~CharArray() { delete Buff; }
int GetLength() { return Length; }
char & operator [](int i);
private:
int Length;
char * Buff;
};

char & CharArray::operator [](int i)
{
static char ch = 0;
if(i<Length&&i>=0)
return Buff[i];
else
{
cout<<"/nIndex out of range.";
return ch;
}
}

void main()
{
int cnt;
CharArray string1(6);
char * string2 = "string";
for(cnt=0; cnt<8; cnt++)
string1[cnt] = string2[cnt];
cout<<"/n";
for(cnt=0; cnt<8; cnt++)
cout<<string1[cnt];
cout<<"/n";
cout<<string1.GetLength()<<endl;
}
  该数组类的优点如下:

  (1) 其大小不心是一个常量。
  (2) 运行时动态指定大小可以不用运算符new和delete。
  (3) 当使用该类数组作函数参数时,不心分别传递数组变量本身及其大小,因为该对象中已经保存大小。

  在重载下标运算符函数时应该注重:

  (1) 该函数只能带一个参数,不可带多个参数。
  (2) 不得重载为友元函数,必须是非static类的成员函数。 2). 重载增1减1运算符

  增1减1运算符是单目运算符。它们又有前缀和后缀运算两种。为了区分这两种运算,将后缀运算视为又目运算符。表达式

  obj++或obj--

  被看作为:

  obj++0或obj--0

  下面举一例子说明重载增1减1运算符的应用。

#include <iostream.h>

class counter
{
public:
counter() { v=0; }
counter operator ++();
counter operator ++(int );
void print() { cout<<v<<endl; }
private:
unsigned v;
};

counter counter::operator ++()
{
v++;
return *this;
}

counter counter::operator ++(int)
{
counter t;
t.v = v++;
return t;
}

void main()
{
counter c;
for(int i=0; i<8; i++)
c++;
c.print();
for(i=0; i<8; i++)
++c;
c.print();
}
  3). 重载函数调用运算符

  可以将函数调用运算符()看成是下标运算[]的扩展。函数调用运算符可以带0个至多个参数。下面通过一个实例来熟悉函数调用运算符的重载。

#include <iostream.h>

class F
{
public:
double operator ()(double x, double y) const;
};

double F::operator ()(double x, double y) const
{
return (x+5)*y;
}

void main()
{
F f;
cout<<f(1.5, 2.2)<<endl;
}

-

资料引用:http://www.knowsky.com/394332.html

<think>好的,我现在要帮用户介绍C++运算符重载。首先,我需要回忆一下运算符重载的基本概念。运算符重载允许用户自定义类型使用C++内置的运算符,比如+、-、*等,使得代码更直观和易读。例如,可以让两个对象直接相加,而不必调用特定的函数。 接下来,我应该考虑用户可能的背景。用户可能是刚开始学习C++,或者已经有一定基础但想深入了解运算符重载。因此,解释需要清晰,从基础开始,逐步深入。可能需要先说明什么是运算符重载,为什么需要它,然后讲解如何实现,包括语法和注意事项。 然后,运算符重载的语法是关键部分。需要详细说明如何定义运算符重载函数,包括成员函数和非成员函数(友元函数)的区别。例如,重载+运算符时,成员函数通常只需要一个参数,因为左操作数是对象本身,而非成员函数需要两个参数。同时,要提到一些运算符必须作为成员函数重载,比如赋值运算符=。 例子是帮助理解的重要部分。我应该举一个简单的例子,比如为自定义的Vector类重载+运算符,这样用户可以看到具体的实现方式。同时,需要区分成员函数和非成员函数的例子,说明它们的不同应用场景。 注意事项和常见问题也不能遗漏。比如不能重载运算符(如.、::、sizeof等),以及重载时保持运算符的原有语义,避免滥用导致代码难以理解。此外,还需要提到运算符的返回类型和参数类型的选择,比如是否返回引用或值,参数的const修饰等。 用户可能还会有疑问,比如运算符重载的使用场景,或者何时应该使用成员函数而非友元函数。因此,在解释过程中需要涵盖这些方面,可能的话,给出一些最佳实践的建议。 最后,总结运算符重载的优点和需要注意的地方,帮助用户全面理解。确保语言通俗易懂,避免过于专业的术语,必要时进行类比,让用户更容易接受。</think>### C++运算符重载详解 #### 1. 什么是运算符重载运算符重载(Operator Overloading)是C++中的一种特性,允许开发者**为自定义类型(如类或结构体)重新定义运算符的行为**。通过重载运算符,可以让对象像内置类型(如`int`、`double`)一样使用`+`、`-`、`*`、`==`等运算符,提升代码可读性和简洁性。 --- #### 2. 如何实现运算符重载运算符重载通过**成员函数**或**全局函数**实现,语法形式为: $$ \text{返回类型 operator 运算符(参数列表)} $$ ##### 示例1:成员函数重载`+` ```cpp class Vector { public: int x, y; // 成员函数重载 + Vector operator+(const Vector& other) { return {x + other.x, y + other.y}; } }; // 使用 Vector v1{1, 2}, v2{3, 4}; Vector v3 = v1 + v2; // 等价于 v1.operator+(v2) ``` ##### 示例2:全局函数重载`<<`(输出流) ```cpp class Student { public: string name; int age; }; // 全局函数重载 << ostream& operator<<(ostream& os, const Student& s) { os << "Name: " << s.name << ", Age: " << s.age; return os; } // 使用 Student s{"Alice", 20}; cout << s; // 输出: Name: Alice, Age: 20 ``` --- #### 3. 常见运算符重载规则 | 运算符类型 | 可重载性 | 示例 | |------------------|----------------|----------------------| | 算术运算符 | `+`, `-`, `*` | `a + b` | | 关系运算符 | `==`, `>`, `<` | `a == b` | | 赋值运算符 | `=`, `+=` | `a = b` | | 下标运算符 | `[]` | `a[0]` | | 函数调用运算符 | `()` | `a(1, 2)` | | **不可重载运算符** | `.`、`::`、`?:`、`sizeof` | 无法重载 | --- #### 4. 关键注意事项 1. **参数限制**: - 至少一个操作数是用户自定义类型(不能全为内置类型)。 - 不能修改运算符的优先级或结合性。 2. **成员函数 vs 全局函数**: - 赋值运算符(`=`)、下标运算符(`[]`)、函数调用运算符(`()`)**必须**作为成员函数重载。 - 输入输出运算符(`>>`、`<<`)通常作为全局函数。 3. **保持语义一致性**: - 例如重载`+`时,不应修改操作数本身,而应返回新对象。 --- #### 5. 完整示例:复数类重载 ```cpp class Complex { private: double real, imag; public: Complex(double r = 0, double i = 0) : real(r), imag(i) {} // 成员函数重载 + Complex operator+(const Complex& other) { return Complex(real + other.real, imag + other.imag); } // 全局友元函数重载 << friend ostream& operator<<(ostream& os, const Complex& c); }; ostream& operator<<(ostream& os, const Complex& c) { os << c.real << " + " << c.imag << "i"; return os; } // 使用 Complex c1(2, 3), c2(4, 5); Complex c3 = c1 + c2; cout << c3; // 输出: 6 + 8i ``` --- #### 6. 应用场景 - 数学计算(向量、矩阵、复数) - 字符串操作(`str1 + str2`) - 容器类(自定义数组、链表) --- #### 7. 总结 **优点**:提升代码直观性,使自定义类型操作更自然。 **注意**:避免过度使用或违反直觉的重载(例如用`+`实现减法)。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值