c++重载运算符

parvinparvin 389 9月11日 发布
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
 
using namespace std;
 
class myComplex3 {
private:
    double real, imag;
 
public:
    myComplex3();
 
    myComplex3(double r, double i);
 
    void outCom();
 
    myComplex3 operator-(const myComplex3 &c);
 
    friend myComplex3 operator+(const myComplex3 &c1, const myComplex3 &c2);
};
 
myComplex3::myComplex3() {
    real = 0;
    imag = 0;
}
 
myComplex3::myComplex3(double r, double i) {
    real = r;
    imag = i;
}
 
void myComplex3::outCom() {
    cout << "(" << real << "," << imag << ")";
}
 
myComplex3 myComplex3::operator-(const myComplex3 &c) {
    return myComplex3(this->real - c.real, this->imag - c.imag);
}
 
myComplex3 operator+(const myComplex3 &c1, const myComplex3 &c2) {
    return myComplex3(c1.real + c2.real, c1.imag + c2.imag);
}
 
int main() {
    myComplex3 c1(1, 2), c2(3, 4), res;
    c1.outCom();
    cout << " operator+ ";
    c2.outCom();
    cout << " = ";
    res = c1 + c2;
    res.outCom();
    cout << endl;
 
    c1.outCom();
    cout << " operator- ";
    c2.outCom();
    cout << " = ";
    res = c1 - c2;
    res.outCom();
    cout << endl;
 
    return 0;
}
 
 
/**
(1,2) operator+ (3,4) = (4,6)
(1,2) operator- (3,4) = (-2,-2)
*/

评论
载入中...