Home » C++ » Summary of const usage in C++

Summary of const usage in C++

The simplest understanding of

const is that it cannot be changed. After that, you can understand the exact content of the const according to the location of the.

The data contents to which the

A. pointer is pointing cannot be changed.

If there is a definition: char str[] = "hello"; then: "
1., const, char, *p = str;

2., char, const, *p = str;

The last two definitions have the same meaning, which means that the data content pointed to by the pointer P cannot be changed.

But you can change the location of the pointer P. That is to say, p[0] = 'a' is illegal, but p = 'hello' is allowed.

Similarly, const char str[] = "hello" is the same,.

The location indicated by the

B. pointer cannot be changed.

1., char*, const, P = str;

P = Hello is illegal, but p[0] = ` a 'is allowed,.


C. function returns the value of const.

Const, Object, get ();


D. member function is const, and the member function cannot change member variables (except for static member variables) when declared,

class Object{
int val;
static int i;
void fun () const
Val = 0; // error. Member variable cannot be changed
I = 0; // is correct; I is static variable


E. parameter is const, consistent with A, B,

copyright notice: This article is original article for blogger. Without permission from blogger,.

must not be reprinted