《C++ Primer》笔记(01)

覆盖内容

第 1 章 开始

笔记

输入输出对象

  • cin标准输入
  • cout标准输出
  • cerr标准错误
  • clog日志信息

输入输出运算符与endl

  • <<>>的左值为对象,右值为输入或输出,返回值为对象;当其作为条件来判断时,效果为检测流的状态(无错误为真,有错误为假)
  • 都为左结合
  • endl为操纵符,结束当前行,并将buffer内容刷到设备中(缓冲刷新)

命名空间

  • 标准库定义都使用std命名空间

注释界定符/**/

  • 不能嵌套,可以使用单行注释符//来对其注释

比较whilefor循环

  • for循环多用于确定次数的循环
  • while循环多用于确定了停止条件的循环

比较i++++i

实现
// 前缀形式:
int& int::operator++() //这里返回的是一个引用形式,就是说函数返回值也可以作为一个左值使用
{//函数本身无参,意味着是在自身空间内增加1的
  *this += 1;  // 增加
  return *this;  // 返回增加后的自身
}

//后缀形式:
const int int::operator++(int) //函数返回值是一个非左值型的,与前缀形式的差别所在。
{//函数带参,说明有另外的空间开辟
  int oldValue = *this;  // 取回值
  ++(*this);  // 增加
  return oldValue;  // 返回增加前的值
}
区别
\ i++ ++i
做左值 X O
返回值 i i+1
i终值 i+1 i+1

头文件引入

  • 使用<>引入标准库,使用""引入非标准库

练习代码

#include <iostream>
#include "Sales_item.h"

int main()
{
	/* 1.4
	std::cout << "Input two numbers:" << std::endl;
	int a, b;
	std::cin >> a >> b;
	std::cout << a << " + " << b << " = " << a + b << std::endl;
	std::cout << a << " * " << b << " = " << a * b << std::endl;
	*/
	
	/* 1.3
	std::cout << "Hello, World." << std::endl;
	*/

	// 1.8
	// std::cout << "/*";// right
	// std::cout << "*/";// right
	// std::cout << /*"*/"*/; // Wrong, /* pair */ first, right="*/
	// std::cout << /*"*/"/*"/*"*/;// right,cout /*

	/* i++ and ++i
	int a,b,i,j;
	a = 0;
	b = 0;
	i = 0;
	j = 0;
	std::cout << "i++ = " << i++ << std::endl;
	std::cout << "++i = " << ++j << std::endl;
	// a++ = ++b; // Wrong
	++a = b++;// ++a return a.new(a=1), b++ return b.old(b=0), a = b let a = b.old = 0;
	std::cout << "++a = b++: a = " << a << "; b = " << b << std::endl;// a=0,b=1
	*/

	/* 1.9
	int sum = 0;
	int i=50;
	while (i <= 100) {
		sum += i;
		++i;
	}
	std::cout << "Sum (50,100) = " << sum << std::endl;
	*/

	/* 1.11
	int a, b;
	std::cin >> a >> b;
	if (a >= b) {
		int temp;
		temp = a;
		a = b;
		b = temp;
	}
	while (a <= b) {
		std::cout << a << " ";
		++a;
	}
	*/

	/* 1.13
	int a, b;
	std::cin >> a >> b;
	if (a >= b) {
		int temp;
		temp = a;
		a = b;
		b = temp;
	}
	for (; a <= b; ++a) {
		std::cout << a << " ";
	}
	*/

	/* 1.16 end by input Ctrl+Z
	int val,sum;
	sum = 0;
	while (std::cin >> val) {
		sum += val;
	}
	std::cout << "Sum = " << sum << std::endl;
	*/

	/* 1.20-1.22
	Sales_item item1, item2, item3;
	std::cin >> item1 >> item2 >> item3;
	std::cout << "Item1 : " << item1 << std::endl;
	std::cout << "Item1 + Item2 + Item3 : " << item1 + item2 + item3 << std::endl;
	*/

	/* 1.23
	Sales_item total;
	int count;
	if (std::cin >> total) {
		count = 1;
		Sales_item trans;
		while (std::cin >> trans) {
			if (total.isbn() == trans.isbn()) {
				total += trans;
				++count;
			}
			else {
				std::cout << "Count = " << count << "Total : " << total << std::endl;
				total = trans;
				count = 1;
			}
		}
		std::cout << "Count = " << count << "Total : " << total << std::endl;
	}
	else {
		std::cerr << "No data" << std::endl;
		return -1;
	}
	*/

	return 0;
}
posted @ 2020-10-27 14:04  1Shen  阅读(90)  评论(0)    收藏  举报