引用
引用的本质
- Type* const ref = &Type_value
- 指针的指向不可修改
static void myPrintA(int &m)
{
m = 100;
return;
}
typedef struct RF_Size {
int& a;
int& b;
}RF_Size_t;
static void myReferenceSize(void)
{
printf("sizeof(RF_Size_t) %d\n", sizeof(RF_Size));
return;
}
static void test_reference_essence(void)
{
int a = 10;
int& ref = a;
ref = 11;
cout << "ref--->" << a << endl;
printf("a: %d\n", a);
printf("ref:%d\n", ref);
printf("&a: %d\n", &a);
printf("&ref: %d\n", &ref);
myPrintA(a);
printf("a: %d\n", a);
myReferenceSize();
return;
}
函数返回的值是引用
static int getAA1()
{
int a;
a = 10;
return a;
}
static int& getAA2()
{
int a;
a = 10;
return a;
}
static int* getAA3()
{
int a;
a = 10;
return &a;
}
static int& g2(int* value)
{
*value = 100;
return *value;
}
static void test_reference_asleftvalue(void)
{
int a1 = 0;
int a2 = 0;
a1 = getAA1();
a2 = getAA2();
int& a3 = getAA2();
printf("a1:%d \n", a1);
printf("a2:%d \n", a2);
printf("a3:%d \n", a3);
int m1 = 10;
m1 = g2(&m1);
int& m2 = g2(&m1);
printf("m1: %d\n", m1);
printf("m2: %d\n", m2);
return;
}
指针的引用
typedef struct Teacher {
char name[64];
int age;
}Teacher_t;
static int getTeacher_1(Teacher_t **myp)
{
Teacher_t* p = (Teacher_t*)malloc(sizeof(Teacher_t));
if (p == NULL)
{
return -1;
}
memset(p,0,sizeof(Teacher_t));
p->age = 33;
*myp = p;
return 0;
}
static int getTeacher_2(Teacher_t* &myP)
{
myP = (Teacher_t*)malloc(sizeof(Teacher_t));
if (myP == NULL)
{
return -1;
}
memset(myP, 0, sizeof(Teacher_t));
myP->age = 35;
return 0;
}
static void test_reference_point(void)
{
Teacher_t* p = NULL;
getTeacher_2(p);
printf("age:%d\n", p->age);
return;
}
常量引用
const int& ref = 10;
- 使用场景: 常量引用主要用来修饰形参,防止误操作
- 在函数形参列表中,可以加const修饰形参,防止形参改变实参
void showValue(const int& v)
{
cout<< v << endl;
}