0
点赞
收藏
分享

微信扫一扫

数据结构-蓄水池算法

 目录

1.const引用

1.1权限的放大 

1.2权限的缩小

2.inline

3.nullptr


1.const引用

1.1权限的放大 

int main() {
	//权限的放大,a只能读值,不能更改,当取a的别名时,b可读值与改值,会报错
	const int a = 10;
    //int& b = a;
    const int& b = a;//这种写法为正确
	return 0;
}

1.2权限的缩小

int main() {
	// 这⾥的引⽤是对b访问权限的缩⼩
	int b = 20;
	const int& rb = b;

	return 0;
}

2.inline

inline(内敛函数)与宏函数类似 

#include<iostream>

using namespace std;

//#define ADD(a, b) ((a) + (b))宏函数
inline int Add(int x, int y)
{
	int ret = x + y;
	ret += 1;
	ret += 1;
	ret += 1;
	return ret;
}
int main()
{
	// 可以通过汇编观察程序是否展开
	// 有call Add语句就是没有展开,没有就是展开了
	int ret = Add(1, 2);

	cout << Add(1, 2) * 5 << endl;
	return 0;
}

3.nullptr

NULL实际是一个宏,在传统的C头文件(stddef.h)中,可以看到如下代码:

#include<iostream>
using namespace std;
void f(int x)
{
cout << "f(int x)" << endl;
}
void f(int* ptr)
{
cout << "f(int* ptr)" << endl;
}
int main()
{
f(0);
// 本想通过f(NULL)调⽤指针版本的f(int*)函数,但是由于NULL被定义成0,调⽤了f(int
x),因此与程序的初衷相悖。
f(NULL);
f((int*)NULL);

// 编译报错:error C2665: “f”: 2 个重载中没有⼀个可以转换所有参数类型
// f((void*)NULL);

f(nullptr);

return 0;
}

nullptr大大减少了我们对null指针访问报错的风险!!!!

举报

相关推荐

0 条评论