例1: int x = 3; //x是变量 int const &y = x; //y是x的引用,但const修饰了 &y 1,x的值可以修改 2,引用y的值不可以修改 |
(1)尝试修改x:
#include<stdlib.h>
#include<iostream>
using namespace std;
int main()
{
int x = 3;
int const &y = x;
x = 9;
cout << "x=" << x << endl;
cout << "y=" << y << endl;
system("pause");
return 0;
}
运行结果:
(2)尝试修改y
#include<stdlib.h>
#include<iostream>
using namespace std;
int main()
{
int x = 3;
int const &y = x; //const修饰y
y= 9; //报错
cout << "x=" << x << endl;
cout << "y=" << y << endl;
system("pause");
return 0;
}
运行结果:编译不通过
1>------ 已启动生成: 项目: ConsoleApplication1, 配置: Debug Win32 ------
1>luoyiran.cpp
1>e:\c++\my c++\consoleapplication1\consoleapplication1\luoyiran.cpp(11): error C3892: “y”: 不能给常量赋值
1>已完成生成项目“ConsoleApplication1.vcxproj”的操作 - 失败。
========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========
例2: int x = 3; 值得注意的是,这种情况居然可以修改y值 |
#include<stdlib.h>
#include<iostream>
using namespace std;
int main()
{
int x = 3;
int& const y = x;
y= 9;
cout << "x=" << x << endl;
cout << "y=" << y << endl;
system("pause");
return 0;
}
运行结果:
例3: void fun(const int &a,const int &b) //传入的值不可更改 |
(1)传入的参数没有const修饰:
#include<stdlib.h>
#include <iostream>
using namespace std;
void fun(int &a, int &b) //传入的参数没有const修饰
{
a = 6;
b = 4;
}
int main()
{
int x = 5;
int y = 6;
fun(x, y); //调用函数
cout << "x=" << x << endl;
cout << "y=" << y << endl;
system("pause");
return 0;
}
运行结果:可以发现,x、y的值改变了。
(2)传入的参数用const修饰:
#include<stdlib.h>
#include <iostream>
using namespace std;
void fun(const int &a,const int &b) // 传入的参数用const修饰
{
a = 6;
b = 4;
}
int main()
{
int x = 5;
int y = 6;
fun(x, y); //调用函数
cout << "x=" << x << endl;
cout << "y=" << y << endl;
system("pause");
return 0;
}
运行结果:编译报错。
1>------ 已启动生成: 项目: love, 配置: Debug Win32 ------
1>love.cpp
1>e:\c++\my c++\love\love\love.cpp(9): error C3892: “a”: 不能给常量赋值
1>e:\c++\my c++\love\love\love.cpp(10): error C3892: “b”: 不能给常量赋值
1>已完成生成项目“love.vcxproj”的操作 - 失败。
========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========