C++ references, assignments, function calls and return values

quote

  1. Reference is to alias the variable, syntax:数据类型 &别名 = 原名

Note 1:

  1. reference must be initialized
  2. Cannot be changed after reference initialization
int a = 10;
int &b = a; // b和a指向同一块内存

int &b; // 错误:没有初始化

int c = 20;
b = c; // 错误:这个写法不是更改引用b,而是把c的值 赋给 b指向的内存,这时候 a和b指向的值都改了

Note 2:

  1. Passing by value will open up a new memory space (copy a copy of data). Formal parameter changes do not affect actual parameters
void swap(a,b) {
    
    
	int temp = a; // 函数运行的时候,会单独再开辟新的 a b temp 内存空间
	a = b;
	b = temp;
	return;
}

void main() {
    
    
	int a = 10;
	int b = 20;
	swap(a,b);
	cout << a << b << endl; // 此时a,b的值并没有发生变化,因为是值传递,形参改变不影响实参
}

  1. If the address is passed, the formal parameter can modify the actual parameter
void swap(int* p1, int* p2) {
    
    
	int temp = *p1;
	*p1 = *p2;
	*p2 = temp;
}

void main() {
    
    
	int a = 10;
	int b = 20;
	swap(&a, &b); // 此时a,b的值已经被交换了。地址传递可以改变实参的值
}

The essence of a reference is a pointer constant

The pointing of the pointer cannot be changed, but the value pointed to by the pointer can be changed

int a = 10;
int &b = a; // 等价于: int * const b = &a
b = 20; // 等价于: *b = 20 编译器优化

Application: Modification of formal parameters to prevent misuse

void func(const int& a) {
    
    
	a = 100; // 错误:形参加了const之后,函数内部不可以再修改该参数的值
	cout << v << endl;
}

int main() {
    
    
	int a = 10;
	func(a);
}

Incorrect usage:

int &b = 10; // 错误:不能编译。引用必须是合法内存空间

Correct (compilation passes) usage:

const int &b = 10; // 可以编译。等价于:int tmep = 10; const int &b = temp;编译器优化
b = 1000; // 错误:加了const后不可以修改变量

Return value by reference
https://blog.csdn.net/weixin_41648259/article/details/106037151

Guess you like

Origin blog.csdn.net/qxqxqzzz/article/details/127342899