c ++ const after the class function add meaning

Our class member functions defined, often have member functions do not change the data members of the class, that is to say, these functions are "read only" function, but there are some functions to modify the value of class data members. If we do not change the data member functions are added to the const keyword is identified, apparently, can improve the readability of the program. In fact, it can improve the reliability of the program, defined as const member functions, and once attempted to modify the data member value, according to the compiler error handling . In fact, there is another role of a const member function, that is, constant objects related to const member functions and const object. For built-in data types, we can define their constants, user-defined classes, too, can define their constant object.
1, behind the non-static const member functions plus (or static member functions applied to the non-member behind gives compiler error)
2 represents a member function implicitly passed this pointer is a pointer const, the member function determines, any modification operation of its members in the class are not allowed (because of this implicit const pointer references);
3, the only exception being modified for mutable members. Plus the const member functions can be called non-const objects and const object, but without the const member functions can only be called a non-const object

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

c ++ function using the front and rear of the action const:

  • Using the return value represents a front const const
  • Const member functions behind the increase in representation of the class can not be amended

Look at these two functions

const int getValue();

int getValue2() const;

/*
 * 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_ */

Realize the source file

/*
 * 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;
}

Guess you like

Origin www.cnblogs.com/YZFHKMS-X/p/11756404.html