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

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

转自:http://blog.csdn.net/zhangss415/article/details/7998123

非静态成员函数后面加const(加到非成员函数或静态成员后面会产生编译错误),表示成员函数隐含传入的this指针为const指针,决定了在该成员函数中,任意修改它所在的类的成员的操作都是不允许的(因为隐含了对this指针的const引用);唯一的例外是对于mutable修饰的成员。加了const的成员函数可以被非const对象和const对象调用,但不加const的成员函数只能被非const对象调用。例如: 

复制代码
 1 class A { 
 2     private: int m_a; 
 3     public: 
 4         A() : m_a(0) {} 
 5          int getA() const  { 
 6              return m_a; //同return this->m_a;。
 7          } 
 8          int GetA() { 
 9              return m_a; 
10          } 
11          int setA(int a) const { 
12              m_a = a; //这里产生编译错误,如果把前面的成员定义int m_a;改为mutable int m_a;就可以编译通过。 
13          } 
14          int SetA(int a)  { 
15              m_a = a; //同this->m_a = a;
16          } 
17 }; 
18 A a1; 
19 const A a2; 
20 int t; 
21 t = a1.getA(); 
22 t = a1.GetA(); 
23 t = a2.getA(); 
24 t = a2.GetA(); //a2是const对象,                    
复制代码
 

调用非const成员函数产生编译错误。 一般对于不需修改操作的成员函数尽量声明为const成员函数,以防止产生const对象无法调用该成员函数的问题,同时保持逻辑的清晰。

补充:

 
c++ 在函数后加const的意义:
   我们定义的类的成员函数中,常常有一些成员函数不改变类的数据成员,也就是说,这些函数是"只读"函数,而有一些函数要修改类数据成员的值。如果把不改变数据成员的函数都加上const关键字进行标识,显然,可提高程序的可读性。其实,它还能提高程序的可靠性,已定义成const的成员函数,一旦企图修改数据成员的值,则编译器按错误处理。 const成员函数和const对象 实际上,const成员函数还有另外一项作用,即常量对象相关。对于内置的数据类型,我们可以定义它们的常量,用户自定义的类也一样,可以定义它们的常量对象。

1、非静态成员函数后面加const(加到非成员函数或静态成员后面会产生编译错误) 2、表示成员函数隐含传入的this指针为const指针,决定了在该成员函数中,     任意修改它所在的类的成员的操作都是不允许的(因为隐含了对this指针的const引用); 3、唯一的例外是对于mutable修饰的成员。     加了const的成员函数可以被非const对象和const对象调用     但不加const的成员函数只能被非const对象调用

char getData() const{         return this->letter;

}

c++ 函数前面和后面 使用const 的作用:

前面使用const 表示返回值为const

后面加 const表示函数不可以修改class的成员

请看这两个函数

const int getValue();

int getValue2() const;


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/*
 * FunctionConst.h
 */

#ifndef FUNCTIONCONST_H_
#define FUNCTIONCONST_H_

class FunctionConst {
public:
    int value;
    FunctionConst();
    virtual ~FunctionConst();
    const int getValue();
    int getValue2(const;
};

#endif /* FUNCTIONCONST_H_ */

源文件中的实现


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/*
 * FunctionConst.cpp 
 */

#include "FunctionConst.h"

FunctionConst::FunctionConst():value(100{
    // TODO Auto-generated constructor stub

}

FunctionConst::~FunctionConst({
    // TODO Auto-generated destructor stub
}

const int FunctionConst::getValue(){
    return value;//返回值是 const, 使用指针时很有用.
}

int FunctionConst::getValue2(const{
    //此函数不能修改class FunctionConst的成员函数 value
    value 15;//错误的, 因为函数后面加 const
    return value;
}

 

原文地址:https://www.cnblogs.com/tsh292278/p/10470628.html