【C++】_002_变量初始化/过滤字符及标点/bitset/const/VC字符串常量

今天花了一下午阅读《C++ Primer》第三至第五章。笔记如下:

1、P52(页码从封面算起):变量初始化规则

#include <string>//使得运算符'<<'可以处理string类型
#include <iostream>//使能标准IO流

int i;//函数外,自动初始化为0

using namespace std;
string s;//默认构造函数,初始化为{0}(空字符串)



void test_p52()
{
	cout << "i == " << i << endl;//输出0
#define _TEST_P52_i2_1
#ifdef _TEST_P52_i2_
	int i2;
	cout << "i2 == " << i2 << endl;//编译错误:使用了未初始化的局部变量"i2"
#endif
	string s2;//默认构造函数,初始化为{0}(空字符串)
	cout << "s[0] == " << (int)s[0] << endl;//输出0
	cout << "s2[0] == " << (int)s2[0] << endl;//输出0
}

2、P90:去除输入字符标点后输出

#include <string>//使得运算符'<<'可以处理string类型
#include <iostream>//使能标准IO流

int ic;//函数外,自动初始化为0

using namespace std;
string sIn;//默认构造函数,初始化为{0}(空字符串)
//string sIn("Hello,World!");//调试后半段功能

void test_p90()
{
	cin >> sIn;
	string sOut(sIn.size(), '\0');//初始化为sIn长度空字符串
	//cout << "sIn == " << sIn.size() << endl;//输出sIn长度
	//cout << "sOut == " << sOut.size() << endl;//输出sOut长度
	int oc = 0;
	char c = 0;
	while ((c = sIn[ic++]) != '\0')
	{
		if (c >= -1 && c <= 255 && !ispunct(c))//排除英文标点及非英文字符
			sOut[oc++] = c;
	}
	cout << "sIn == " << sIn << endl;//输出sIn
	cout << "sOut == " << sOut << endl;//输出sOut
}

3、P103:bitset类类型初步应用

#include <bitset>//引入bitset类类型
#include <iostream>//使能标准IO流

using namespace std;
bitset<4> b;//生成4位二进制集

void test_p103()
{
	b.set(2);
	cout << "b = " << b << "B" << endl;
}

4、const修饰引用时可能不起作用,cosnt引用可能不随定义它的变量变化而变化。

#include <iostream>//引入标准IO流

using namespace std;//引入标准函数库

void test_p122()
{
	//1、const无效化
	int a = 0;
	const int &ra = a;//ra和a地址相同,const无意义

	a = 100;

	cout << "a = " << a << endl;//输出a = 100
	cout << "ra = " << ra << endl;//输出ra = 100,ra随a变化

	//2、引用与变量'异步'
	int b = 0;
	const int &rb = b + 1;//可以解构为1、const int tmp = a + 1; 2、const int &ra = tmp;因此实际上rb和b地址不同

	b = 100;

	cout << "b = " << b << endl;//输出b = 100
	cout << "rb = " << rb << endl;//输出rb = 1,rb不随b变化


}


5、P140:VC不遵守ANSI-C规则之“初始化指针的时候创建的字符串常量被定义为只读”,而是可读。

#include <iostream>//引入标准IO流

using namespace std;//引入标准函数库

void test_p140()
{
	//1、指针字符串默认只读,VC此处不遵循ANSI-C规则
	char *pStr = "123";
	pStr[0] = '0';

	//2、因此为了保证兼容性,尽量在需要时添加const限定符
	const char *cpStr = "123";
	//cpStr[0] = '0';//无法编译:const不能赋值
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值