- 函数重载
- 运算符重载
- 类型转换重载
文章目录
运算符重载
- 用成员函数重载运算符
- 用友元重载运算符
- 重载增量运算符
- []和()的重载
- new和delete的重载
- 赋值运算符的重载
- 不能重载的运算符:
.
、*
、::
、?
、sizeof
- 只能重载已有的运算符,不能创造新的
- 编译器预定义了
=
、&
、,(顺序)
:三种运算符,不必重载可直接使用 - =运算符重载必须用成员函数,不能使用全局函数进行重载
- 多种类型进行混合运算的运算符成员函数一般采用全局函数的形式
运算符重载的目的
- 运算符重载使得用户自定义的数据以一种更简洁的方式工作
运算符重载函数的定义
- 运算符重载时,运算符函数只能定义为两种方式
(1)成员函数:必须是实例成员函数
(2)全局函数 - 重载应注意的问题
(1)优先级和结合顺序不变
(2)不能改变目数
(3)类外定义至少有一个相应类的参数 - 运算符成员函数:调用成员函数的对象隐式成为表达式的第一个运算数
- 外部运算符函数:第一个参数直接对应表达式的第一个运算数
- 实例成员函数实现运算符重载
class Point {
public: // 构造函数
Point() {
}
Point(int x, int y) : x(x), y(y) {
}
public: // 运算符重载
Point operator+(Point pt) {
Point p;
p.x = this->x + pt.x;
p.y = this->y + pt.y;
return p;
}
public:
void show() {
cout << "(" << x << "," << y << ")" << endl;
}
private:
int x;
int y;
};
int main(int argc, char *argv[], char *envp[]) {
Point p1(1, 2), p2(3, 4);
// 运算符重载
Point p12 = p1 + p2;
p12.show();
// 对象的函数调用: 方法名为: operator+
Point p34 = p1.operator+(p2);
p34.show();
system("pause");
return 0;
}
- 全局函数实现运算符重载
class Point {
friend Point operator+(Point, Point p2);
public:
Point(){
}
Point(int x, int y) : x(x), y(y) {
}
public: // 运算符重载函数如果是成员函数: 就必须是实例成员函数
//static Point operator+(Point p1, Point p2) {
// Point p;
// p.x = p1.x + p2.x;
// p.y = p1.y + p2.y;
// return p;
//}
public:
void show() {
cout << "(" << x << "," << y << ")" << endl;
}
private:
int x;
int y;
};
Point operator+(Point p1, Point p2) {
Point p;
p.x = p1.x + p2.x;
p.y = p1.y + p2.y;
return p;
}
int main(int argc, char *argv[], char *envp[]) {
Point p1(1, 2), p2(3, 4);
Point p12 = p1 + p2;
p12.show();
// 全局函数名称: operator+
Point p34 = operator+(p1, p2);
p34.show();
system("pause");
return 0;
}
- 这两种方式非常相似,关键区别在于
(1)成员函数具有 this 指针
(2)全局函数没有this指针
用成员函数重载运算符
- 运算符通过运算符函数重载
- 运算符函数是一种特殊的成员函数,语法形式为
type operator@([参数]) {
}
一元运算符
- 一元运算符,不论是前缀还是后缀,都需要一个操作数
aa@ 或 @aa
- 类的成员函数:
aa.operator@()
:一元运算符函数operator @
所需的一个操作数由对象 aa通过this
指针隐含地传递,因此参数表为空。这时运算符函数用类的成员函数 表示 - 全局函数:
operator @ (aa)
:一元运算符函数operator @
所需的一个操作数在参数表中由对象显式地提供,适用于没有this
指针的情况。这时运算符函数用类的友员函数表示
二元运算符
aa @ bb
-
类的成员函数:
aa.operator @ (bb)
:二元运算符函数operator @
所需的一个操作数由对象aa通过 this 指针隐含地传递。因此它只有一个参数。这时运算符函数用类的 成员函数表示 -
全局函数:
operator@(aa , bb)
:二元运算符函数operator@
所需的两个操作数在参数表中由对象 aa 和 bb显式地提供,适用于没有this指针的情况。这时运算符函数用类的 友员函数 表示 -
C++能够被重载的运算符
+ - * / % ^ & | ~
! = < > += -= *= /= %=