算术运算符、赋值运算符、插入提取运算符的重载
时间: 2023-07-11 12:41:59 浏览: 55
算术运算符、赋值运算符、插入提取运算符都可以在 C++ 中重载。
1. 算术运算符重载:
在 C++ 中,可以重载的算术运算符包括加(+)、减(-)、乘(*)、除(/)、取模(%)等。重载时需要定义相应的成员函数或全局函数。
例如,重载加法运算符+的成员函数定义如下:
```cpp
class MyClass {
public:
MyClass operator+(const MyClass& other) const {
// 进行加法运算
return result;
}
};
```
2. 赋值运算符重载:
在 C++ 中,赋值运算符=可以被重载。赋值运算符重载函数的返回值通常是该类对象的引用。
例如,重载赋值运算符=的成员函数定义如下:
```cpp
class MyClass {
public:
MyClass& operator=(const MyClass& other) {
// 进行赋值操作
return *this;
}
};
```
3. 插入提取运算符重载:
在 C++ 中,插入运算符<<和提取运算符>>可以被重载以支持输入输出操作。
例如,重载插入运算符<<的全局函数定义如下:
```cpp
ostream& operator<<(ostream& os, const MyClass& obj) {
os << obj.data;
return os;
}
```
重载提取运算符>>的全局函数定义如下:
```cpp
istream& operator>>(istream& is, MyClass& obj) {
is >> obj.data;
return is;
}
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)