相关知识:
- 递增和递减一般是改变对象的状态,所以一般是重载为成员函数。
- 重载递增递减,一定要和指针的递增递减区分开。因为这里的重载操作的是对象,而不是指针(由于指针是内置类型,指针的递增递减是无法重载的),所以一般情况的递增递减是操作对象内部的成员变量。
- 递增和递减分为前置和后置情况,a = ++b;(前置), a = b++;(后置)。因为符号一样,所以给后置版本加一个int形参作为区分,这个形参是0,但是在函数体中是用不到的,只是为了区分前置后置;注意,int 在 括号内是为了向编译器说明这是一个后缀形式,而不是表示整数。
- 前缀形式重载调用 Check operator ++ () ,后缀形式重载调用 operator ++ (int)。
代码涉及内容:
- 自增自减操作符:
++
--
- 重载前缀形式,后缀形式的自增自减操作符:
operator++();
operator++(int);
- 前置递增就是增加当前对象的值,并且返回当前对象;
- 后置递增就是增加当前对象的值,并且返回增加之前的该对象;
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
81
82
83
84
85
86
87
88
89
90
using namespace std;
class String
{
public:
String(char const *chars = "");
String(String const &str);
~String();
void display() const;
String &operator++(); // 前++ ++s
String const operator++(int); // 后++ s++
private:
char *ptrChars;
};
String &String::operator++()
{
for (std::size_t i = 0; i < std::strlen(ptrChars); ++i)
{
++ptrChars[i];
}
return *this;
}
String const String::operator++(int)
{
String copy(*this);
++(*this);
return copy;
}
void String::display() const
{
cout << ptrChars << endl;
}
String::String(char const *chars)
{
// 如果指针是空指针就赋值成空字符串;
chars = chars ? chars : "";
ptrChars = new char[std::strlen(chars) + 1];
std::strcpy(ptrChars, chars);
}
String::String(String const &str)
{
ptrChars = new char[std::strlen(str.ptrChars) + 1];
std::strcpy(ptrChars, str.ptrChars);
}
String::~String()
{
delete[] ptrChars;
}
int main()
{
int x = 5;
x++;
++x;
cout << x << endl;
String s("ABC");
s.display();
++s;
s.display();
s++;
s.display();
cout << endl << endl;
String str1("ABC");
str1.display();
String str2(++str1);
str2.display();
String str3(str1++);
str3.display();
str1.display();
cout << "hello HTL2018" << endl;
return 0;
}程序执行结果:
参考链接:
C++ ++ 和 – 运算符重载