1.初学C++
C++简介:C++融合了3种不同的编程方式:C语言代表的过程性语言、C++在C语言基础上添加的类代表的面向对象语言、 C++模板支持的泛型编程。学习C++时需要掌握C语言的知识、OOP知识以及泛型编程注释。
1.1C++预处理器和iostream文件
如果程序要使用C++输入或输出工具
先提供两行代码
#include <iostream>
using namespace std;
注:使用cin和cout进行输入和输出程序必须包含文件iostream
1.2头文件名,名称空间
iostream也叫头文件,被包含再文件起始处。
使用下面的名称空间编译指令来使iostream中的定义对程序可用
1.3C++初始化
1.3.1变量初始化的五种方式
int main()
{
int a=10;
int b(10);
int c{10};
int d=int(10);
int e=int{ 10 };
//指针初始化
int* f=NULL;
int* g{NULL};
}
1.3.2数组初始化
int main()
{
//数组初始化
int arr[10]={1,2,3};
int b[10]{1,2,3};
int c[]={1,2,3};
int d[]{1,2,3};
}
2如何防止读入时候对字符串的越界处理
调用函数的_s函数,因为有安全保护。
2.1输入输出
对象 | 含义 | 对应设备 | 对应的类 | c语言中相应文件的标准文件 | |
cin | 标注输入流 | 键盘 | istream_withassign | stdin | |
cout | 标注输出流 | 屏幕 | ostream_withassign | stdout | |
cerr | 标注错误流 | 屏幕 | ostream_withassign | stderr | |
clog | 标注错误流 | 屏幕 | ostream_withassign | stderr |
2.2控制符,换行符
2.2.1控制符endl
endl是一个特殊的C++符号,表示一个重要的概念:重起一行。
例:
cout<<"The Good ,the";
cout<<"Bad,";
cout<<"and the Ukulele";
cout<<endl;
如果省略endl其输出将如下:
The Good,theBad,and the Uklele
2.2.2换行符
C++还提供了另一种在输出中指示换行的旧式方法:\n
\n被视为一个字符,即为换行符,换行符是一种被称为“转义序列”的按键组合。
3.const
3.1cons指针的示例
3.1.1const修饰变量
int a=10,b=20;
const int* p=&a;
int* s0=p;//编译错误
const int* s1=p;
int* const s2=p;
const int* const s3=p;
3.1.2const修饰指针
int a=10,b=20;
int* p1=&a;
const int* p2=&a;
int const* p3=&a;
int* cinst p4=&a;
const int* const p5=&a;
3.1.3const修饰变量本身
int main()
{
int a=10
int* const p=&a;
int s1=p;//true
const int* s2=p;//true
int* const s3=p;//true
const int* const s4=p;//true