1
2
| const int nValue = 5; // initialize explicitly const integerconst int nValue2(7); // initialize implicitly cont integer |
1
2
| const Date cDate; // initialize using default constructorconst Date cDate2(10, 16, 2020); // initialize using parametrized constructor |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| class Something{public: int m_nValue; Something() { m_nValue = 0; } void ResetValue() { m_nValue = 0; } void SetValue(int nValue) { m_nValue = nValue; } int GetValue() { return m_nValue; }};int main(){ const Something cSomething; // calls default constructor cSomething.m_nValue = 5; // violates const cSomething.ResetValue(); // violates const cSomething.SetValue(5); // violates const return 0;} |
1
| std::cout << cSomething.GetValue(); |
1
2
3
4
5
6
7
8
9
10
11
12
| class Something{public: int m_nValue; Something() { m_nValue = 0; } void ResetValue() { m_nValue = 0; } void SetValue(int nValue) { m_nValue = nValue; } int GetValue() const { return m_nValue; }}; |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| class Something{public: int m_nValue; Something() { m_nValue = 0; } void ResetValue() { m_nValue = 0; } void SetValue(int nValue) { m_nValue = nValue; } int GetValue() const;};int Something::GetValue() const{ return m_nValue;} |
1
2
3
4
5
6
7
| class Something{public: int m_nValue; void ResetValue() const { m_nValue = 0; }}; |
1
2
3
4
5
6
7
8
| class Something{public: int m_nValue; const int& GetValue() const { return m_nValue; } int& GetValue() { return m_nValue; }}; |
1
2
3
4
5
| Something cSomething;cSomething.GetValue(); // calls non-const GetValue();const Something cSomething2;cSomething2.GetValue(); // calls const GetValue(); |
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
| class Date{private: int m_nMonth; int m_nDay; int m_nYear; Date() { } // private default constructorpublic: Date(int nMonth, int nDay, int nYear) { SetDate(nMonth, nDay, nYear); } void SetDate(int nMonth, int nDay, int nYear) { m_nMonth = nMonth; m_nDay = nDay; m_nYear = nYear; } int GetMonth() { return m_nMonth; } int GetDay() { return m_nDay; } int GetYear() { return m_nYear; }}; |
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
| class Date{private: int m_nMonth; int m_nDay; int m_nYear; Date() { } // private default constructorpublic: Date(int nMonth, int nDay, int nYear) { SetDate(nMonth, nDay, nYear); } void SetDate(int nMonth, int nDay, int nYear) { m_nMonth = nMonth; m_nDay = nDay; m_nYear = nYear; } int GetMonth() const { return m_nMonth; } int GetDay() const { return m_nDay; } int GetYear() const { return m_nYear; }}; |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| void PrintDate(const Date &cDate){ // although cDate is const, we can call const member functions std::cout << cDate.GetMonth() << "/" << cDate.GetDay() << "/" << cDate.GetYear() << std::endl;}int main(){ const Date cDate(10, 16, 2020); PrintDate(cDate); return 0;} |


0 comments: