C++有这样一段代码
#include<stdio.h>
void swap(int &x, int &y)
{
int tmp = x;
x = y;
y = tmp;
}
int main(void)
{
int a = 1, b = 2;
printf("a=%d, b=%d\n", a, b);
swap(a, b);
printf("a=%d, b=%d\n", a, b);
return 0;
}
这里面的 & 表示是引用调用,也就是直接将实参传到函数,而不是将实参拷贝给形参,然后形参传进函数,所以这样的方式可以更改实参的值。
void avoidchange(const int x)
书上说const关键字可以防止函数内部修改参数,那么这样的方式是调用的时候将实参拷贝给形参,然后对形参进行操作,那么就算改变了形参的值又有什么影响呢?
所以说这种情况下这样使用const应该是没有必要的吧?
还是说应该这样使用
void avoidchange(const int & x)
这样将实参直接传给函数,就少了拷贝给形参的过程,所以会更快(int参数还不明显,假如是某个比较大的结构体或者类对象就更为明显了),但是这种情况下可能不想在函数内部更改传入的实参,所以就要加个const既提醒开发者,又提醒编译器。
我这样的理解是不是对的?
另外对于const、以及C++函数的定义和调用还有哪些需要知道的知识点?
As far as real development practice is concerned, in most cases const is used to modify the memory address, because inside the function, the memory address is very likely to be modified. For parameter access, even if you access the variable (this is different from the memory address ) for modification, it can also be modified through memory access. The author can discuss these issues by looking at the actual application,
const
also has another effect: writingconst
after the class method can indicate that the method will not have side effects on this object. In this way, modifying getter and other functions can improve the efficiency of the code generated by the compiler.Case 1: It is necessary. Indeed, as you said, even if the variables are changed inside the function, it will not affect the external actual parameters. This qualifier is for the formal parameters inside the function. Then, add The qualifier indicates that you do not want this variable to be modified in the function. In other words, you can use whatever value the function writer wants to pass, and do not modify it inside the function.
Case 2: const can also modify the class Properties and methods, you can check the information for details.