C++ constant parameter constant return value constant member function

  • 2020-05-24 05:51:29
  • OfStack

1. Constant parameter
When the parameter has the top-level const or the low-level const, it is ok to pass it the constant object or the non-constant object. In this case, we mainly consider that the parameter does not have const, while the argument has const. In fact, it is also 10 points simple.

2. Constant return value
It's also easy to skip over.

3. Constant member functions
const in a constant function is used to modify *this in the following form:


int f() const{```}

And then this becomes interesting
The default type of *this is type *const this. The this pointer has a top-level const, but there is no low-level const. Due to the limitation of low-level const, the argument of low-level const cannot be copied to the default version of *this, that is to say, the reference or pointer of the constant object cannot call the member function of the default version of *this.
That's not all...
We just made it clear that an argument with the underlying const cannot initialize the default version of *this, but can an object with the top-level const initialize the default version of *this and call a function?
No..


// define 1 A simple class student
class student{
public:
  string name;
  int number;
public :
  student() :name("lili"), number(0){ }// The constructor 
  string Name(){return name;}// Nonconstant member function 
  int Number() const{return number;}// Constant member function 

};
// Now define 1 A constant student object 
const student s1;
s1.Name();// An error 
s1.Number();// correct 

In fact, the following initialization occurs when we call s1.Name () :


student *const this=&s1;

This is equivalent to the following process:


const student *s1;
student *const this=s1;

Obviously s1 has a bottom const and this does not. Initialization failed.
Similarly, if one argument is int *const p, then when initializing this, it will be converted to const int *const p. There is one underlying const and the initialization fails.
Overview: constant objects, Pointers to or references to constant objects can only call constant member functions.


Related articles: