引用基本语法: 类型 &别名 = 原名
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
//引用基本语法: 类型 &别名 = 原名
void test01()
{
int a = 10;
int &b = a;
b = 100;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
int main() {
test01();
//test02();
//test03();
return EXIT_SUCCESS;
}
### 引用的注意事项
- 引用必须要初始化
- 引用一旦初始化后,就不可以引向其他变量
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
//引用基本语法: 类型 &别名 = 原名
void test01()
{
int a = 10;
int &b = a;
b = 100;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
void test02()
{
int a = 10;
//int &b; //引用必须要初始化
int &b = a;
//引用一旦初始化后,就不可以引向其他变量
int c = 100;
b = c; // 赋值
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
}
int main() {
//test01();
test02();
//test03();
return EXIT_SUCCESS;
}
指针引用
- 双指针
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
struct Person
{
int age;
};
void allocate_one(Person** p){
*p = (Person* )malloc(sizeof(Person));
(*p)->age = 10;
};
void test01(){
Person *p = nullptr;
allocate_one(&p);
cout<<"p.age = "<<p->age<<endl;
}
int main() {
test01();
// test02();
// system("pause");
return EXIT_SUCCESS;
}
- 传递引用
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
struct Person
{
int age;
};
void allocate_two(Person* &p){
p = (Person* )malloc(sizeof(Person));
p->age = 10;
};
void test02(){
Person *p = nullptr;
allocate_two(p);
cout<<"p.age = "<<p->age<<endl;
}
int main() {
test02();
// system("pause");
return EXIT_SUCCESS;
}
常量引用
#include <cstdlib>
#include <iostream>
using namespace std;
void test01(){
const int &ref = 10;// 加了const之后, 相当于写成 int temp = 10; const int &ref = temp;
int *p = (int*)&ref;
*p = 1000;
cout << ref << endl;
};
void showValue(const int &a)
{
// a = 100000;//常量引用的使用场景 修饰函数中的形参,防止误操作
int *p = (int*)(&a);
* p = 10000;
cout << "a = " << a << endl;
};
void test02(){
int a = 100;
showValue(a);
}
int main(){
test01();
test02();
return EXIT_SUCCESS;
}