函数声明后面的const用法 void function() const{}

拼搏现实的明天。 2022-06-07 06:45 311阅读 0赞

通常我们会看到一些函数声明后面会跟着一个const,这个const是做什么的呢?

看一下下面的例子,就知道了。直接在编译前,就会提示下面的两个错误

复制代码

  1. // test1107.cpp : 定义控制台应用程序的入口点。
  2. //
  3. #include "stdafx.h"
  4. #include <iostream>
  5. using namespace std;
  6. class aa{
  7. int num;
  8. public:
  9. aa(){
  10. int b =10;
  11. num = b;
  12. };
  13. void out1(){
  14. cout<<num<<endl;
  15. }
  16. void out2() const{
  17. cout<<num<<endl;
  18. }
  19. void out3() const{
  20. num+=10; //出错,const函数不能修改其数据成员
  21. cout<<num<<endl;
  22. }
  23. };
  24. int _tmain(int argc, _TCHAR* argv[])
  25. {
  26. aa a1;
  27. a1.out1();
  28. a1.out2();
  29. a1.out3();
  30. const aa a2;
  31. a2.out1(); // 错误,const的成员 不能访问非const的函数
  32. a2.out2();
  33. a2.out3();
  34. return 0;
  35. }

复制代码

在类成员函数的声明和定义中,

const的函数不能对其数据成员进行修改操作。

const的对象,不能引用非const的成员函数。

http://www.cnblogs.com/xing901022/p/3413019.html

发表评论

表情:
评论列表 (有 0 条评论,311人围观)

还没有评论,来说两句吧...

相关阅读

    相关 C\C++中函数后面const

    我们定义的类的成员函数中,常常有一些成员函数不改变类的数据成员,也就是说,这些函数是"只读"函数,而有一些函数要修改类数据成员的值。如果把不改变数据成员的函数都加上const关

    相关 const用法详解

    面向对象是C++的重要特性. 但是c++在c的基础上新增加的几点优化也是很耀眼的 就const直接可以取代c中的\define 以下几点很重要,学不好后果也也很严重