Home  >  Article  >  Backend Development  >  const qualifier for C++ function reference parameters

const qualifier for C++ function reference parameters

王林
王林Original
2024-04-19 21:42:01444browse

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.

C++ 函数引用参数的 const 限定符

C const qualifier for function reference parameters

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 symbol

Semantics

  • A const reference parameter represents a reference to a constant object that cannot be modified directly inside the function.
  • The function can modify the member variables or elements indirectly referenced by the object passed by the const reference.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn