c++中关于const的用法有很多,const既可以修饰变量,也可以函数,不同的环境下,是有不同的含义。今天来讲讲const加在函数前和函数后面的区别。比如:

01 #include<iostream>
02  
03 using namespace std;
04  
05 // Ahthor:  过往记忆
06 // E-mail:  wyphao.2007@163.com
07 // Blog:    http://www.iteblog.com
08 // 转载请注明出处
09  
10 class TestClass {
11 public:
12     size_t length() const;
13     const char* getPContent();
14     void setLengthValid(bool isLengthValid);
15 private:
16     char *pContent;
17     size_t contentLength;       //A
18     bool lengthIsValid;         //B
19     size_t precontentLength;
20 };
21  
22 size_t TestClass::length() const{ //函数名后加const
23     if(!lengthIsValid){
24         contentLength= strlen(pContent);    //C
25         lengthIsValid = true;           //D
26     }
27  
28     return contentLength;
29 }
30  
31 const char* TestClass::getPContent(){//函数名前加const
32     return pContent;
33 }
34  
35 void TestClass::setLengthValid(bool isLengthValid){
36     lengthIsValid = isLengthValid;
37 }
38  
39 int main(void){
40     TestClass *tc =new TestClass;
41     tc->setLengthValid(false);
42     tc->length();
43     char * content = tc->getPContent();      //E
44     return 0;
45 }

其中类TestClass中的length函数和getPContent函数分别在函数名后和前加了const修饰符,如果试图编译上面的代码,将会得到下面的错误:

1 --------------------配置: mingw5 - CUI Debug, 编译器类型: MinGW--------------------
2 检查文件依赖性...
3 正在编译 C:\Users\wyp\Desktop\未命名1.cpp...
4 [Error] C:\Users\wyp\Desktop\未命名1.cpp:24: error: assignment of data-member `TestClass::contentLength' in read-only structure
5 [Error] C:\Users\wyp\Desktop\未命名1.cpp:25: error: assignment of data-member `TestClass::lengthIsValid' in read-only structure
6 [Error] C:\Users\wyp\Desktop\未命名1.cpp:43: error: invalid conversion from `const char*' to `char*'
7 [Warning] C:\Users\wyp\Desktop\未命名1.cpp:45:2: warning: no newline at end of file
8  
9 构建中止 未命名1: 3 个错误, 1 个警告

里面有三个错误,也就是代码C、D、E处的三个地方。为什么C和D处的代码会出错,原因如下
length函数名的后面加了const修饰符,这样说明函数的成员对象是不允许修改的。我们都知道,在类的成员函数里面,默认是在成员函数的第一个位置
是this指针,如果在成员函数(只能是成员函数,要是类的静态函数或者是非成员函数就不可以在函数名后面加上const)后面const,则说明
this指针的值是不可以修改的,只能读取。而上面的length函数可能会修改里面的contentLength和lengthIsValid的值,这
样编译器肯定是不允许的,所以这样是会出现错误的。
解决方法是:在类的A、B处的成员前面加上mutable修饰符:

1 mutable size_t contentLength;   //A
2 mutable bool lengthIsValid;     //B

从字面的意思知道,mutalbe是“可变的,易变的”,跟constant(既C++中的const)是反义词。在C++中,mutable也是
为了突破const的限制而设置的。被mutable修饰的变量,将永远处于可变的状态,即使在一个const函数中。这样在C、D处将不会出错。
那么,为什么E处出现了错误。这是因为在函数名getPContent前加了const修饰符,意味着该函数返回的值只能是读取,而不能被修改。而E处的content却为char *是可以被修改的,这与const正好相反了,所以出现了错误。解决方法是:在char *前面加上const修饰符,即:

1 const char * content = tc->getPContent(); //E

再去编译运行,这样就不会出现错误了。

from: http://www.iteblog.com/archives/214)

[Reprint]C++函数前和函数后加const修饰符区别的更多相关文章

  1. C++函数前和函数后加const修饰符区别

    class Test(){ public: Test(){} const int foo(int a); const int foo(int a) const; }; 一.概念 当const在函数名前 ...

  2. C++ 成员函数前和函数后加const修饰符区别

    博客转载自: https://www.iteblog.com/archives/214.html 分析以下一段程序,阐述成员函数后缀const 和 成员函数前const 的作用 #include< ...

  3. 函数后面的const修饰符的作用

    比如 void Fun() const; 的const是修饰什么的? 其实是修饰this指向的对象的. 这篇文章很详细的说明了const的作用,其中第三点说明了这种const的作用:const的用法, ...

  4. C++中的const成员函数(函数声明后加const,或称常量成员函数)用法详解

    http://blog.csdn.net/gmstart/article/details/7046140 在C++的类定义里面,可以看到类似下面的定义: 01 class List { 02 priv ...

  5. 【VS开发】【C++开发】const在函数前与函数后的区别

    const在函数前与函数后的区别 一   const基础           如果const关键字不涉及到指针,我们很好理解,下面是涉及到指针的情况:           int   b   =   ...

  6. C++: C++函数声明的时候后面加const

    C++: C++函数声明的时候后面加const 转自:http://blog.csdn.net/zhangss415/article/details/7998123 非静态成员函数后面加const(加 ...

  7. const修饰符与函数

    一.用const修饰函数的参数 函数参数类型前加const指明该参数为常量,在函数内部不可改变. void func(const int x) { //x不可以在内部进行赋值等操作. } 注:当参数为 ...

  8. Delphi 中 函数参数中的 const 修饰符的本质以及注意事项

    来自:http://blog.csdn.net/farrellcn/article/details/9096787 ------------------------------------------ ...

  9. 字符串输出输入函数,const修饰符,内存分区,动态内存管理,指针和函数,结构体

    1.字符串输出输入函数 读入字符串的方法: 1) scanf 特点:不能接收空格 2) gets 特点:可以接受含有空格的字符串 ,不安全 3) fgets(); 特点:可以帮我们自动根据数组的长度截 ...

随机推荐

  1. Flink Internals

    https://cwiki.apache.org/confluence/display/FLINK/Flink+Internals   Memory Management (Batch API) In ...

  2. 阻止默认行为stopDefault

    function stopDefault(e){ if(e && e.preventDefault) e.preventDefault(); else window.event.ret ...

  3. Eclipse下使用Ant 【转】

    官方在线帮助文档:http://ant.apache.org/manual/index.html 中文汉化 帮助文档:http://www.cnblogs.com/pengxl/archive/201 ...

  4. 使用C++还是QML

    本质上,Qt 是一个C++类库.在引入 QML 以前,所有的开发都是基于 C++ 的,但到了 Qt 5,QML 和 Qt Quick 成为了 Qt 的核心之一,导致很多初学者在犹豫是否还需要学习 C+ ...

  5. C code 字符串与整数的相互转化

    #include<stdio.h> int str_to_int(const char *str,int *num); void int_to_str(char str[],const i ...

  6. JQuery通过$(xxx...)返回对象

    var JQ = function () { return new JQ.prototype.init(); }; JQ.prototype.init = function () { }; JQ.pr ...

  7. struts.xml 配置详解

    struts.xml是我们在开发中利用率最高的文件,也是Struts2中最重要的配置文件. 一下分别介绍一下几个struts.xml中常用到的标签 1.<include> 利用includ ...

  8. [LeetCode]题解(python):054-Spiral Matrix

    题目来源 https://leetcode.com/problems/spiral-matrix/ Given a matrix of m x n elements (m rows, n column ...

  9. 解决调用context.Session["NAME"]时总出现Object reference not set to an instance of an object.异常的方法

    if (context.Session != null) { }

  10. 设置tomcat的编码为utf-8

    <Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" ...