Home >Backend Development >C++ >const qualifier for C++ function reference parameters
In C, the const qualifier is used for reference parameters to represent a reference to a constant object that cannot be modified directly inside the function. A function can modify member variables or elements indirectly referenced by an object passed by a const reference. This is crucial to ensure that the function does not accidentally modify the object passed to it.
In C, the const
qualifier can be used to modify reference parameters , to indicate that the objects they point to cannot be modified during function execution.
Syntax
void func(const T& param);
Among them:
func
: Function name T
: Type of reference parameter&
: Reference symbolSemantics
Practical case
Consider the following example:
struct Person { int age; string name; }; void printPerson(const Person& person) { cout << "Age: " << person.age << endl; // 允许访问常量对象的成员变量 person.age = 100; // 错误:尝试修改常量对象 }
In this example, the printPerson
function accepts a const Person reference as argument. The function can access the age
member variable of person
, but cannot modify it because person
is a constant object.
Another example:
void swap(int& a, int& b) { int temp = a; a = b; b = temp; }
In this example, the swap
function accepts two integer references as parameters. Functions can modify variables passed by reference because they are not const objects.
Summary
Decorating reference parameters with the const qualifier can help ensure that a function does not accidentally modify the object passed to it. This is important to prevent programming errors and improve code maintainability.
The above is the detailed content of const qualifier for C++ function reference parameters. For more information, please follow other related articles on the PHP Chinese website!