C++ Little White Textbook Exercise 1

Practice cout cin input and output

#include <iostream>
#include <string>
using namespace std;

int main() {
    
    
	int oneInt1, oneInt2;
	char strArray[20];
	string str;
	double oneDouble;
	char oneChar = 'a';
	cout << "输入两个整型值,一个字符,一个字符串和一个浮点值";
	cout << "以空格、Tab键或 《Enter》键分割:" << endl;
	cin >> oneInt1 >> oneInt2 >> oneChar >> strArray >> oneDouble;
	str = strArray;
	cout << "输入的数据时:" << endl;

	cout << "字符串是:\t\t" << str << endl
		<< "两个整型分别是:\t" << oneInt1 << "和\t" << oneInt2 << endl
		<< "字符是:\t\t" << oneChar << "\n"
		<< "浮点值是:\t\t" << oneDouble << endl;
	return 0;
}

Practice forced type conversion

#include <iostream>
using namespace std;
int main() {
    
    
	int a = 10;
	const int*p = &a;
	const int ca = 30;
	int *q;
	cout << "a的地址为:\t" << &a << "\ta的值为:\t" << a << endl;
	cout << "*p指向的地址为:" << p << "\t*p的值为:\t" << *p << endl;
	q = const_cast<int *>(p);
	*q = 20;
	cout << "a的地址为:\t" << &a << "\ta的值为:\t" << a << endl;
	cout << "*p指向的地址为:" << p << "\t*p的值为:\t" << *p << endl;
	cout << "*q指向的地址为:" << q << "\t*q的值为:\t" << *q << endl;

	cout << "分界线" << endl;
	p = &ca;
	q = const_cast<int *>(p);
	*q = 40;
	cout << "ca的地址为:\t" << &ca << "\tca的值为:\t" << ca << endl;
	cout << "*p指向的地址为:" << p << "\t*p的值为:\t" << *p << endl;
	cout << "*q指向的地址为:" << q << "\t*q的值为:\t" << *q << endl;
	return 0;
}

Practice the default values ​​of function parameters

#include <iostream>
using namespace std;
void func(int a = 11, int b = 22, int c = 33)
{
    
    
	cout << "a=" << a << ",b=" << b << ",c=" << c << endl;

}
int main() {
    
    
	func();//调用是缺少了3个实参,将使用定义中的3个参数默认值
	func(55);//调用是缺少了后两个实参,将使用定义中的后两个参数默认值
	func(77, 99);//调用时缺少了最后1个实参,将使用定义中的最后1个参数默认值
	func(8, 88, 888);//调用时实参完备,将不使用定义中的任何参数默认值
	return 0;
}

//C++ 语言规定,提供默认值时必须按从右到左的顺序提供,即有默认值的形参必须在形参列表的最后。
//如果有某个形参没有默认值,则它左侧的所有形参都不能有默认值
void defaultvalue(int = 2, double = 3.0);
void defaultcalue2(int a, double b = 3.0);

void defalutvalue3(int a = 2, double b);//报错

void func1(int a, int b = 2, int c = 3);
void func2(int a = 1, int b, int c = 3); //报错
void func3(int a = 1, int b = 2, int c); //报错

Guess you like

Origin blog.csdn.net/weixin_42292697/article/details/114993809