类成员函数后边加const

  本文主要整理自stackoverflow上的一个对问题Meaning of “const” last in a C++ method declaration?的回答。

测试1

  对于下边的程序,关键字const的作用在哪里?

 1 #include <iostream>
 2 
 3 class MyClass
 4 {
 5 private:
 6     int counter;
 7 public:
 8     void Foo()
 9     { 
10         std::cout << "Foo" << std::endl;    
11     }
12 
13     void Foo() const
14     {
15         std::cout << "Foo const" << std::endl;
16     }
17 
18 };
19 
20 int main()
21 {
22     MyClass cc;
23     const MyClass& ccc = cc;
24     cc.Foo();
25     ccc.Foo();
26 
27     return 0;
28 }

  程序输出:

Foo
Foo const

  当我们将函数“void Foo()”注释掉,测试程序将会输出:

Foo const
Foo const

  当我们将“void Foo() const”注释掉,测试程序不通过。因为“void Foo()”并不是返回一个const的MyClass,所以“const MyClass& ccc = cc”这一句是通不过编译的。

  

  综上,对函数“void Foo() const”而言,它不能够修改类MyClass的所有成员变量的值(即此时类MyClass是const的),否则将编译不通过。

  所以下边的程序也是通不过编译的:

 1     void Foo()
 2     {
 3         counter++; //this works
 4         std::cout << "Foo" << std::endl;    
 5     }
 6 
 7     void Foo() const
 8     {
 9         counter++; //this will not compile
10         std::cout << "Foo const" << std::endl;
11     }

测试2

  对于测试1的程序,我们只要将成员变量counter设置为mutable就可以在“void Foo() const”函数中修改counter的值了,具体测试程序如下:

 1 #include <iostream>
 2 
 3 class MyClass
 4 {
 5 private:
 6     mutable int counter;
 7 public:
 8 
 9     MyClass() : counter(0) {}
10 
11     void Foo()
12     {
13         counter++;
14         std::cout << "Foo" << std::endl;    
15     }
16 
17     void Foo() const
18     {
19         counter++;
20         std::cout << "Foo const" << std::endl;
21     }
22 
23     int GetInvocations() const
24     {
25         return counter;
26     }
27 };
28 
29 int main(void)
30 {
31     MyClass cc;
32     const MyClass& ccc = cc;
33     cc.Foo();
34     ccc.Foo();
35     std::cout << "The MyClass instance has been invoked " << ccc.GetInvocations() << " times" << endl;
36 
37     return 0;      
38 }
原文地址:https://www.cnblogs.com/xiehongfeng100/p/4706186.html