mook 离港篇之 引用 与 const

本文深入探讨了C++中引用的概念及其初始化必要性,并详细解释了const关键字在不同上下文中的使用方式,包括对变量、引用及指针的限定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引用是变量的别名

思考:能不能只有别名 ------不能------引用必须初始化



// ConsoleApplication14.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include<iostream>
#include "stdio.h"
using namespace std;
typedef struct
{
int x;
int y;
}Coord;//结构体名字,注意后面分号,}后面没;,名字后面有;
int main(void)
{
Coord  c;
Coord &c1 = c;
c1.x = 10;
c1.y = 20;
cout << c.x << "  " << c.y<<endl;//do not foget endl
system("pause");
}






F9 设置断点 调试

// ConsoleApplication14.cpp : 定义控制台应用程序的入口点。
//

这样不也是可以的??
#include "stdafx.h"
#include<iostream>
#include "stdio.h"
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
printf("交换之后m和n的值是:m = %d, n = %d\n",a, b);
}
int main()
{
int m = 1, n = 2;
swap(m, n);
//printf("交换之后m和n的值是:m = %d, n = %d\n",m,n);
system("pause");
return 0;
}


控制变量的const:

对类型:

const int x 代表x不能变

对引用:

const int&y=x   即代表 y不能变   const int x 代表x不能变

对指针:

const int*p=&x 代表p地址不能变  == int const*p=&x                           

int*const p=&x 代表x(*p),即对象,不能变   


const  int  x=3;int  *y=&x   不行  有风险   可以通过改变*y改变x,这相当于用权限大的代表权限小的不可以,用权限小的可变性代表大的是可以的

#include"stdafx.h"
#include <iostream>
using namespace std;
#define X3//也是定义一个常量  但是宏定义  不检查语法错  推荐用const
int main(void)
{
//const int x = 3;
int x = 3;
//const int*p = &x;均可
//const int*p = &x;
//*p = 5;//不行
//x = 5;


//int*const p = &x;
int y = 5;
//p = &y;  不可
//*p = 10;  可以


//yinyong
int const &z = x;
//z = 10;  不可
x = 10;//keyi


//fan(x, y);不可  因为函数里面用了const
system("pause");
return 0;
}
void fan(const int &a, const int &b)
{
a = 10;
b = 20;
}


指针指向const修饰的变量时,应该是const int const *p = &a; 而不是int const a=3,int *p=&a  因为这个时候可以通过改*p改a  是不对的







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值