类成员函数后边加const

本文深入解析C++中const修饰符在方法声明中的作用,包括其如何限制成员函数修改对象状态,以及mutable关键字如何绕过这些限制。通过具体代码示例展示了const成员函数的使用场景和编译行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  本文主要整理自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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值