C++运算符重载实例

本文用C++写两个自定义类的例子,主要练习一下运算符重载。

point类

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
69
70
71
72
73
74
75
76
77
78
79
80
#include <stdio.h>
#include <iostream>
using namespace std;
class point
{
public:
point(int xx, int yy):x(xx), y(yy) {}
point& operator=(point &a)
{
printf("operator=\n");
x = a.x;
y = a.y;
return *this;
}
point operator+(point &a)
{
printf("operator+\n");
return point(x+a.x, y+a.y);
}
point operator-(point &a)
{
printf("operator-\n");
return point(x-a.x, y-a.x);
}
point& operator++()
{
printf("operator前++\n");
x++;
y++;
return *this;
}
point operator++(int)
{
printf("operator后++\n");
point a = *this;
x++;
y++;
return a;
}
point& operator--()
{
printf("operator前--\n");
x--;
y--;
return *this;
}
point operator--(int)
{
printf("operator后--\n");
point a = *this;
x--;
y--;
return a;
}
bool operator==(point &a)
{
printf("operator==\n");
return x==a.x && y==a.y;
}
void show()
{
printf("x=%d,y=%d\n", x, y);
}
private:
int x;
int y;
};
int main()
{
point a(3, 4);
point b(5, 5);
point c = a + b;
c.show();
point d = c;
d.show();
++a;
a++;
d = a;
return 0;
}

String类

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
#include <iostream>
#include <string.h>
using namespace std;
class String
{
public:
String(const char *str = NULL);
String(const String &other);
~String();
String& operator=(const String &other);
private:
char *m_data;
};
String::~String()
{
cout<<"析构函数"<<endl;
delete [] m_data;
}
String::String(const char *str)
{
cout<<"普通构造函数"<<endl;
if (str == NULL) {
m_data = new char[1];
*m_data = 0;
} else {
int length = strlen(str);
m_data = new char[length+1];
strcpy(m_data, str);
}
}
String::String(const String &other)
{
cout<<"拷贝构造函数"<<endl;
int length = strlen(other.m_data);
m_data = new char[length+1];
strcpy(m_data, other.m_data);
}
String& String::operator=(const String &other)
{
cout<<"赋值函数"<<endl;
if (this == &other)
return *this;
delete [] m_data;
int length = strlen(other.m_data);
m_data = new char[length+1];
strcpy(m_data, other.m_data);
return *this;
}
int main()
{
String s1("hello");
String s2(s1);
String s3 = s2;
s3 = s1;
return 0;
}