const member functions
A const member function is a class member function that may not make any changes to any of the data members of the class. A const member function is identified by appending the keyword, const, to both the prototype and the heading of the function definition.
The following example demonstrates const member functions. It constains several compilation errors.
1 // File: ex3-8.cpp – const member functions
2
3 void makeit6(int& I)
4 {
5 I = 6;
6 }
7
8
9 class ABC
10 {
11 int x;
12 public:
13 void funk();
14 void gunk() const; // const member function
15 void hunk(int&);
16 void junk(int&) const; // const member function
17 void lunk(const int&);
18 void munk(const int&) const; // const member function
19 };
20
21 void ABC::funk()
22 {
23 x = 6; // ok
24 makeit6(x); // ok
25 makeit6(6); // error: cannot convert const int to int&
26 }
27
28 void ABC::gunk() const
29 {
30 x = 6; // error: cannot change data member in CMF
31 makeit6(x); // error: cannot pass const int as int&
32 }
33
34 void ABC::hunk(int &I)
35 {
36 x = 6; // ok
37 makeit6(I); // ok
38 makeit6(x); // ok
39 }
40
41 void ABC::junk(int &I) const
42 {
43 x = I; // error: cannot change data member in CMF
44 makeit6(I); // ok
45 makeit6(x); // error: cannot pass const int as int&
46 }
47
48
49 void ABC::lunk(const int &I)
50 {
51 x = I; // ok
52 makeit6(I); // error: cannot pass const int& as int&
53 makeit6(x); // ok
54 }
55
56 void ABC::munk(const int &I) const
57 {
58 x = I; // error: cannot change data member in CMF
59 makeit6(I); // error: cannot pass const int& as int&
60 makeit6(x); // error: cannot pass const int as int&
61 }
62
63
64 int main()
65 {
66 ABC object;
67 int i = 3;
68 object.funk();
69 object.gunk();
70 object.hunk(i);
71 object.junk(i);
72 object.lunk(i);
73 object.munk(i);
74
75 return 0;
76 }No output – compile errors
Make sure that you are clear on the difference between a const member function and one with a reference to const argument.
Note: in example 3-8 above, lunk() is not a const member function. It is a member function with a reference to const argument.
const member function 是 class member function, 它無法變更 class 的 data members.
沒有留言:
張貼留言