Skip to content

Commit

Permalink
operator overload. (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
tadpoleswiminyangtze authored Apr 24, 2024
1 parent 4a0e93f commit af343ad
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 4 deletions.
3 changes: 0 additions & 3 deletions day05/07complex/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,12 @@
* 左右操作数均可为左值或右值
* 表达式的值为右值
* 成员函数形式

```
class LEFT {
const RESULT operator#(const RIGHT& right) const { ... }
};
```

* 全局函数形式

```
const RESULT operator#(const LEFT& left, const RIGHT& right) { ... }
```
Expand Down
2 changes: 2 additions & 0 deletions day05/09complex/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# 单目操作运算符重载

## 运算类单目操作符:-、~、!等

* 操作数为左值或右值
* 表达式的值为右值
* 成员函数形式
Expand Down
1 change: 0 additions & 1 deletion day05/10complex/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
* 操作数为左值
* 表达式的值为左值,且为操作数本身(而非副本)
* 成员函数形式

```
class OPERAND {
OPERAND& operator#() { ... }
Expand Down
21 changes: 21 additions & 0 deletions day05/10complex/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,24 @@ class Complex {
return *this;
}

const Complex operator++(int) {
Complex old = *this;
++*this;
return old;
}

friend Complex& operator--(Complex& o) {
--o.m_r;
--o.m_i;
return o;
}

friend const Complex operator--(Complex& o, int) {
Complex old = o;
--o;
return old;
}

private:
int m_r;
int m_i;
Expand All @@ -31,8 +43,17 @@ int main() {
Complex c2 = ++++c1; // c1.operator++().operator++();
c1.print(); // 3 + 4i
c2.print(); // 3 + 4i

c2 = ----c1;
c2.print(); // 1 + 2i

c2 = c1++; // c2 = c1.operator++(0)
c1.print(); // 2 + 3i
c2.print(); // 1 + 2i

c2 = c1--;
c1.print(); // 1 + 2i
c2.print(); // 2 + 3i

return 0;
}

0 comments on commit af343ad

Please sign in to comment.