运算符重载与this指针
时间: 2024-03-18 21:20:01 浏览: 16
运算符重载是指在类中对C++内置运算符进行重新定义的过程,使得运算符能够适用于类对象。C++中的运算符重载可以通过成员函数和非成员函数两种方式实现。
this指针是一个指向当前对象的指针,它在成员函数中使用。在运算符重载中,this指针可以用来引用当前对象的成员变量和成员函数。
例如,在一个矩形类中重载“+”运算符,可以通过以下两种方式实现:
1. 成员函数方式:
```c++
class Rectangle {
public:
int width, height;
Rectangle operator+(const Rectangle& other) {
Rectangle result;
result.width = this->width + other.width;
result.height = this->height + other.height;
return result;
}
};
```
在上述代码中,重载了“+”运算符,并使用了成员函数的方式实现。在函数中使用了this指针来引用当前对象的成员变量。
2. 非成员函数方式:
```c++
class Rectangle {
public:
int width, height;
};
Rectangle operator+(const Rectangle& r1, const Rectangle& r2) {
Rectangle result;
result.width = r1.width + r2.width;
result.height = r1.height + r2.height;
return result;
}
```
在上述代码中,重载了“+”运算符,并使用了非成员函数的方式实现。在函数中没有使用this指针,而是直接引用了两个参数对象的成员变量。
总结:运算符重载中可以使用this指针来引用当前对象的成员变量和成员函数。但是,在非成员函数的方式中无法使用this指针,需要通过参数来引用对象的成员变量。