【c++初阶】:(1)c++入门基础知识
目录
1. c++的第一个程序
C++兼容C语言绝大多数的语法,所以C语言实现的hello world依旧可以运行,C++中需要把定义文件代码后缀改为.cpp,vs编译器看到是.cpp就会调用C++编译器编译,下面分别展示用c语言和c++语言书写的hello world代码。
c语言版本: // test.cpp #include<stdio.h> int main() { printf("hello world\n"); return 0; } c++版本: // test.cpp // 这⾥的std cout等我们都看不懂,没关系,下⾯我们会依次讲解 #include<iostream> using namespace std; int main() { cout << "hello world\n" << endl; return 0; }2. 命名空间
2.1 namespace的价值
在C/C++中,变量、函数和后面要学到的类都是大量存在的,这些变量、函数和类的名称将都存在于全局作用域中,可能会导致很多冲突。使用命名空间的目的是对标识符的名称进行本地化,以避免命名冲突或名字污染,namespace关键字的出现就是针对这种问题的。
在c语⾔项目中,类似下面程序这样的命名冲突是普遍存在的问题,所以C++引入namespace就是为了更好的解决这样的问题。
#include <stdio.h> #include <stdlib.h> int rand = 10; int main() { // 编译报错:error C2365: “rand”: 重定义;以前的定义是“函数” printf("%d\n", rand); return 0; }2.2 namespace的定义
定义命名空间,需要使⽤到namespace关键字,后⾯跟命名空间的名字,然后接⼀对{}即可,{}中即为命名空间的成员。命名空间中可以定义变量/函数/类型等。namespace本质是定义出⼀个域,这个域跟全局域各自独立,不同的域可以定义同名变量,所以下⾯的rand不再冲突了。C++中域有函数局部域,全局域,命名空间域,类域;域影响的是编译时语法查找⼀个变量/函数/类型出处(声明或定义)的逻辑,所有有了域隔离,名字冲突就解决了。局部域和全局域除了会影响编译查找逻辑,还会影响变量的⽣命周期,命名空间域和类域不影响变量生命周期。namespace只能定义在全局,当然他还可以嵌套定义。项目工程中多文件中定义的同名namespace会认为是⼀个namespace,会进行自动合并,所以不会产生冲突。C++标准库都放在⼀个叫std(standard)的命名空间中。
以下代码展示了namespace的一些定义的使用:
#include <stdio.h> #include <stdlib.h> // 1. 正常的命名空间定义 namespace bit { // 命名空间中可以定义变量/函数/类型 int rand = 10; int Add(int left, int right) { return left + right; } struct Node { struct Node* next; int val; }; } int main() { // 这⾥默认是访问的是全局的rand函数指针 printf("%p\n", rand); // 这⾥指定bit命名空间中的rand printf("%d\n", bit::rand); return 0; } //2. 命名空间可以嵌套 namespace bit { // 鹏哥 namespace pg { int rand = 1; int Add(int left, int right) { return left + right; } } // 杭哥 namespace hg { int rand = 2; int Add(int left, int right) { return (left + right)*10; } } } int main() { printf("%d\n", bit::pg::rand); printf("%d\n", bit::hg::rand); printf("%d\n", bit::pg::Add(1, 2)); printf("%d\n", bit::hg::Add(1, 2)); return 0; } // 多⽂件中可以定义同名namespace,他们会默认合并到⼀起,就像同⼀个namespace⼀样 // Stack.h #pragma once #include<stdio.h> #include<stdlib.h> #include<stdbool.h> #include<assert.h> namespace bit { typedef int STDataType; typedef struct Stack { STDataType* a; int top; int capacity; }ST; void STInit(ST* ps, int n); void STDestroy(ST* ps); void STPush(ST* ps, STDataType x); void STPop(ST* ps); STDataType STTop(ST* ps); int STSize(ST* ps); bool STEmpty(ST* ps); } // Stack.cpp #include"Stack.h" namespace bit { void STInit(ST* ps, int n) { assert(ps); ps->a = (STDataType*)malloc(n * sizeof(STDataType)); ps->top = 0; ps->capacity = n; } // 栈顶 void STPush(ST* ps, STDataType x) { assert(ps); // 满了, 扩容 if (ps->top == ps->capacity) { printf("扩容\n"); int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2; STDataType* tmp = (STDataType*)realloc(ps->a, newcapacity * sizeof(STDataType)); if (tmp == NULL) { perror("realloc fail"); return; } ps->a = tmp; ps->capacity = newcapacity; } ps->a[ps->top] = x; ps->top++; } //... } // Queue.h #pragma once #include<stdlib.h> #include<stdbool.h> #include<assert.h> namespace bit { typedef int QDataType; typedef struct QueueNode { int val; struct QueueNode* next; }QNode; typedef struct Queue { QNode* phead; QNode* ptail; int size; }Queue; void QueueInit(Queue* pq); void QueueDestroy(Queue* pq); // ⼊队列 void QueuePush(Queue* pq, QDataType x); // 出队列 void QueuePop(Queue* pq); QDataType QueueFront(Queue* pq); QDataType QueueBack(Queue* pq); bool QueueEmpty(Queue* pq); int QueueSize(Queue* pq); } // Queue.cpp #include"Queue.h" namespace bit { void QueueInit(Queue* pq) { assert(pq); pq->phead = NULL; pq->ptail = NULL; pq->size = 0; } // ... } // test.cpp #include"Queue.h" #include"Stack.h" // 全局定义了⼀份单独的Stack typedef struct Stack { int a[10]; int top; }ST; void STInit(ST* ps){} void STPush(ST* ps, int x){} int main() { // 调⽤全局的 ST st1; STInit(&st1); STPush(&st1, 1); STPush(&st1, 2); printf("%d\n", sizeof(st1)); // 调⽤bit namespace的 bit::ST st2; printf("%d\n", sizeof(st2)); bit::STInit(&st2); bit::STPush(&st2, 1); bit::STPush(&st2, 2); return 0; } 2.3 命名空间的使用
编译查找一个变量的声明/定义时,默认只会在局部或者全局查找,不会到命名空间里面去查找。所以下面程序会编译报错;所以我们要使用命名空间中的变量/函数时,我们可以使用下面三种方式:
- 指定命名空间访问,项目中经常使用的方式。
- using将命名空间中的某个成员展开,项目中经常访问的不存在冲突的成员推荐使用这种方式。
- 展开命名空间中的全部成员,项目中不推荐使用这种方法,因为产生命名冲突的风险很大,日常小练习程序为了方便的话推荐使用。
#include<stdio.h> namespace N { int a = 0; int b = 1; } int main() { // 编译报错:error C2065: “a”: 未声明的标识符 printf("%d\n", a); return 0; } // 指定命名空间访问 int main() { printf("%d\n", N::a); return 0; } // using将命名空间中某个成员展开 using N::b; int main() { printf("%d\n", N::a); printf("%d\n", b); return 0; } // 展开命名空间中全部成员 using namespce N; int main() { printf("%d\n", a); printf("%d\n", b); return 0; } 3. c++输入&输出
<iostream>是Input Output Stream的缩写,是标准的输入、输出流库,定义了标准的输入、输出对象。std::cin是istream类的对象,它主要面向窄字符(narrow characters(of type char))的标准输入流。std::cout是ostream类的对象,它主要面向窄字符的标准输出流。std::endl是一个函数,流插入输出时,相当于插入一个换行字符加刷新缓冲区。<<是流插入运算符,>>是流提取运算符。(c语言中还用这两个运算符做位运算左移/右移)使用c++输入输出会变得更加方便,不需要像printf/scanf输入输出时那样,需要手动指定格式,c++的输入输出可以自动识别变量类型(本质是通过函数重载实现的),其实最重要的是c++的流能够更好的支持自定义类型对象的输入和输出。IO流涉及类和对象,运算符重载,继承等很多面向对象的知识,这些知识后面会进行学习,所以这里只能简单认识一下c++IO流的用法,后面会有专门的章节来学习IO流库。cout/cin/endl等都属于c++标准库,c++标准库都放在一个叫std(standard)的命名空间中,所以要通过命名空间的使用方式去用他们。一般日常练习中我们可以使用"using namespace std"来对std的内容全部展开,但是实际的项目开发中不建议这样使用。下面的演示代码中并没有包含"#include<stdio.h>"也可以使用printf和scanf是因为在<iostream>中间接包含了,vs系列的编译器是这样的,但是对于其他编译器可能会产生报错。
演示代码如下:
#define _CRT_SECURE_NO_WARNINGS 1 #include <iostream> using namespace std; int main() { int a = 0; double b = 0.1; char c = 'x'; cout << a << " " << b << " " << c << endl; std::cout << a << " " << b << " " << c << std::endl; scanf("%d%lf", &a, &b); printf("%d %lf\n", a, b); // 可以⾃动识别变量的类型 cin >> a; cin >> b >> c; cout << a << endl; cout << b << " " << c << endl; return 0; } #include<iostream> using namespace std; int main() { // 在io需求⽐较⾼的地⽅,如部分⼤量输⼊的竞赛题中,加上以下3⾏代码 // 可以提⾼C++IO效率 ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); return 0; } 4. 缺省参数
缺省参数是声明或定义函数时为函数的参数指定一个缺省值。在调用函数时,如果没有指定实参则采用该形参的缺省值,否则使用指定的实参,缺省参数分为全缺省或半缺省参数。(有些地方把缺省参数也叫默认参数)全缺省就是全部形参给缺省值,半缺省就是部分形参给缺省值,。c++规定半缺省参数必须从右往左依次连续缺省,不能间隔跳跃给缺省值。带缺省参数的函数调用,c++规定必须从左向右依次给实参,不能跳跃给实参。函数声明和定义分离时,缺省参数不能在函数声明和定义中同时出现,规定必须函数声明给缺省值。
演示代码如下:
#include <iostream> #include <assert.h> using namespace std; void Func(int a = 0) { cout << a << endl; } int main() { Func(); // 没有传参时,使⽤参数的默认值 Func(10); // 传参时,使⽤指定的实参 return 0; } #include <iostream> using namespace std; // 全缺省 void Func1(int a = 10, int b = 20, int c = 30) { cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl << endl; } // 半缺省 void Func2(int a, int b = 10, int c = 20) { cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl << endl; } int main() { Func1(); Func1(1); Func1(1,2); Func1(1,2,3); Func2(100); Func2(100, 200); Func2(100, 200, 300); return 0; } // Stack.h #include <iostream> #include <assert.h> using namespace std; typedef int STDataType; typedef struct Stack { STDataType* a; int top; int capacity; }ST; void STInit(ST* ps, int n = 4); // Stack.cpp #include"Stack.h" // 缺省参数不能声明和定义同时给 void STInit(ST* ps, int n) { assert(ps && n > 0); ps->a = (STDataType*)malloc(n * sizeof(STDataType)); ps->top = 0; ps->capacity = n; } // test.cpp #include"Stack.h" int main() { ST s1; STInit(&s1); // 确定知道要插⼊1000个数据,初始化时⼀把开好,避免扩容 ST s2; STInit(&s2, 1000); return 0; } 5. 函数重载
C++支持在同一作用域中出现同名函数,但是要求这些同名函数的形参不同,可以是参数个数不同或者类型不同。这样C++函数调用就表现出了多态行为,使用更加灵活。C语言是不支持同一作用域中出现同名函数的。
#include<iostream> using namespace std; // 1、参数类型不同 int Add(int left, int right) { cout << "int Add(int left, int right)" << endl; return left + right; } double Add(double left, double right) { cout << "double Add(double left, double right)" << endl; return left + right; } // 2、参数个数不同 void f() { cout << "f()" << endl; } void f(int a) { cout << "f(int a)" << endl; } // 3、参数类型顺序不同 void f(int a, char b) { cout << "f(int a,char b)" << endl; } void f(char b, int a) { cout << "f(char b, int a)" << endl; } // 返回值不同不能作为重载条件,因为调⽤时也⽆法区分 //void fxx() //{} // //int fxx() //{ // return 0; //} // 下⾯两个函数构成重载 // f()但是调⽤时,会报错,存在歧义,编译器不知道调⽤谁 void f1() { cout << "f()" << endl; } void f1(int a = 10) { cout << "f(int a)" << endl; } int main() { Add(10, 20); Add(10.1, 20.2); f(); f(10); f(10, 'a'); f('a', 10); return 0; } 6. 引用
6.1 引用的概念和定义
引用不是新定义⼀个变量,⽽是给已存在变量取了⼀个别名,编译器不会为引⽤变量开辟内存空间, 它和它引⽤的变量共用同一块内存空间。比如:⽔壶传中李逵,宋江叫"铁牛",江湖上人称"黑旋风";林冲,外号豹⼦头;
用法:类型& 引用别名=引用对象;
#include<iostream> using namespace std; int main() { int a = 0; // 引⽤:b和c是a的别名 int& b = a; int& c = a; // 也可以给别名b取别名,d相当于还是a的别名 int& d = b; ++d; // 这⾥取地址我们看到是⼀样的 cout << &a << endl; cout << &b << endl; cout << &c << endl; cout << &d << endl; return 0; } 6.2 引用的特性
引用在定义时必须进行初始化,即必须指明是对哪个变量进行引用。一个变量可以有多个引用。引用一旦绑定到一个实体(如变量、对象等),就无法再重新绑定到另一个实体。这与指针不同,指针可以随时指向不同的内存地址,而引用在初始化后必须始终指向最初绑定的实体。
#include <iostream> using namespace std; int main() { int a = 10; int b = 20; int& ref = a; // ref现在是a的别名 cout << "ref: " << ref << endl; // 输出10(a的值) ref = b; // 注意:这里并不是让ref引用b,而是将b的值赋给a(因为ref绑定的是a) cout << "a: " << a << endl; // 输出20(a的值被修改) cout << "ref: " << ref << endl; // 输出20(ref仍然是a的别名) // int& ref2; // 错误!引用必须初始化 return 0; }6.3 引用的使用
引用在实践中主要是用引用传参和引用做返回值可以减少拷贝,提高效率,而且在改变引用对象时同时还可以改变被引用对象。引用传参和指针传参的功能是类似的,但引用传参相对会更简单一点。引用返回值的场景相对比较复杂,在本章节学习中只简单讲解一些场景,还有一些内容在后面的类和对象学习中会详细讲解。引用和指针在实践中相辅相成,功能具有重叠性,但各有各的特点,互相不可代替。C++的引用与其他语言的引用(如JAVA)是具有很大的区别的,除了用法之外,最大的不同点在于,C++引用定义后不能改变指向,JAVA的引用可以改变指向。一些主要用C语言代码实现版本的数据结构教材中,使用C++引用代替指针传参,目的是为了简化程序,避开复杂的指针,但是很多同学并没有学习过引用的使用方法,所以经常会看的一头雾水。
void Swap(int& rx, int& ry) { int tmp = rx; rx = ry; ry = tmp; } int main() { int x = 0, y = 1; cout << x <<" " << y << endl; Swap(x, y); cout << x << " " << y << endl; return 0; } #include<iostream> using namespace std; typedef int STDataType; typedef struct Stack { STDataType* a; int top; int capacity; }ST; void STInit(ST& rs, int n = 4) { rs.a = (STDataType*)malloc(n * sizeof(STDataType)); rs.top = 0; rs.capacity = n; } // 栈顶 void STPush(ST& rs, STDataType x) { assert(ps); // 满了, 扩容 if (rs.top == rs.capacity) { printf("扩容\n"); int newcapacity = rs.capacity == 0 ? 4 : rs.capacity * 2; STDataType* tmp = (STDataType*)realloc(rs.a, newcapacity * sizeof(STDataType)); if (tmp == NULL) { perror("realloc fail"); return; } rs.a = tmp; rs.capacity = newcapacity; } rs.a[rs.top] = x; rs.top++; } // int STTop(ST& rs) int& STTop(ST& rs) { assert(rs.top > 0); return rs.a[rs.top]; } int main() { // 调⽤全局的 ST st1; STInit(st1); STPush(st1, 1); STPush(st1, 2); cout << STTop(st1) << endl; STTop(st1) += 10; cout << STTop(st1) << endl; return 0; } #include<iostream> using namespace std; typedef struct SeqList { int a[10]; int size; }SLT; // ⼀些主要⽤C代码实现版本数据结构教材中,使⽤C++引⽤替代指针传参,⽬的是简化程序,避开复 杂的指针,但是很多同学没学过引⽤,导致⼀头雾⽔。 void SeqPushBack(SLT& sl, int x) {} typedef struct ListNode { int val; struct ListNode* next; }LTNode, *PNode; // 指针变量也可以取别名,这⾥LTNode*& phead就是给指针变量取别名 // 这样就不需要⽤⼆级指针了,相对⽽⾔简化了程序 //void ListPushBack(LTNode** phead, int x) //void ListPushBack(LTNode*& phead, int x) void ListPushBack(PNode& phead, int x) { PNode newnode = (PNode)malloc(sizeof(LTNode)); newnode->val = x; newnode->next = NULL; if (phead == NULL) { phead = newnode; } else { //... } } int main() { PNode plist = NULL; ListPushBack(plist, 1); return 0; }6.4 const引用
可以引用一个const对象,但是必须用const引用。const引用也可以引用普遍对象,因为对象的访问权限在引用过程中可以缩小,但是不能对访问权限进行放大。需要注意的是类似int& rb = a + b; double d = 12.36; int& rd = d;这种被引用对象是表达式或者存在数据类型转换的场景,表达式计算结果会被保存在一个临时对象中,同时int& rb = b在类型转换过程中会产生临时对象存储中间值,也就是说rb和ra引用的都是临时对象,而C++规定临时对象具有常性,所以这里就导致引用之后,访问权限被放大,这是不被允许的行为,所以这时需要使用const引用来防止访问权限放大。 所谓临时对象就是编译器需要一个空间暂存表达式的求值结果时临时创建的一个未被命名的对象,C++中把这个未命名对象叫做临时对象。
int main() { const int a = 10; // 编译报错:error C2440: “初始化”: ⽆法从“const int”转换为“int &” // 这⾥的引⽤是对a访问权限的放⼤ //int& ra = a; // 这样才可以 const int& ra = a; // 编译报错:error C3892: “ra”: 不能给常量赋值 //ra++; // 这⾥的引⽤是对b访问权限的缩⼩ int b = 20; const int& rb = b; // 编译报错:error C3892: “rb”: 不能给常量赋值 //rb++; return 0; } #include<iostream> using namespace std; int main() { int a = 10; const int& ra = 30; // 编译报错: “初始化”: ⽆法从“int”转换为“int &” // int& rb = a * 3; const int& rb = a*3; double d = 12.34; // 编译报错:“初始化”: ⽆法从“double”转换为“int &” // int& rd = d; const int& rd = d; return 0; } 6.5 引用和指针的关系
C++中的指针和引用在实践中是相辅相成的,他们的功能具有重叠性,但是又各自有各自的特点,互相是不可替代的。
语法概念上引用是一个变量的取别名不开空间,指针是存储一个变量的地址,要开空间。引用在定义时必须进行初始化,指针建议进行初始化,但是在语法上并不是必须的。引用在初始化时引用一个对象后,就不能再印用其他对象,而一个指针可以不断地改变指向对象。引用可以直接访问指向对象,而指针需要进行“解引用”才可以访问到指向对象。sizeof中含义不同,引用结果为引用类型的大小,但是指针始终是地址空间所占的字节个数(32位平台下占4个字节,64位平台下占8个字节)。指针很容易出现空指针和野指针的问题,但是引用很少会出现这种问题(不代表不会出现),引用使用起来相对安全一点。
#include <iostream> using namespace std; int main() { double x = 3.14; double& ref = x; // 引用绑定到x double* ptr = &x; // 指针指向x cout << "sizeof(x): " << sizeof(x) << endl; // double类型的大小(通常8字节) cout << "sizeof(ref): " << sizeof(ref) << endl; // 引用返回被引用对象的大小(8字节) cout << "sizeof(ptr): " << sizeof(ptr) << endl; // 指针本身的大小(32位平台4字节,64位平台8字节) return 0; }7. inline
用inline修饰的函数叫做内联函数,编译时C++编译器会在调用的地方展开内联函数,这样调用内联函数就需要建立栈帧了,就可以提高效率。inline对于编译器而言只是一个建议,也就是说,加了inline编译器也可以选择在调用的地方不展开,不同编译器关于inline什么情况展开各不相同,因为C++标准没有规定这个。inline适用于频繁调用的短小函数(比如Swap函数),对于递归函数或者代码相对多一些的函数,就算加上inline也会被编译器忽略。C语言实现宏函数也会在预处理时替换展开,但是宏函数实现很复杂且很容易出现错误,同时也不方便进行调试,C++设计inline目的就是代替C语言的宏函数。VS编译器在debug版本下默认是不展开inline的,这样方便调试,如果debug版本下想展开需要设置一下以下两个地方。inline不建议声明和定义分离到两个文件(一般建议inline的声明和定义都写在头文件(.h)中),分离会导致链接错误。因为inline被展开就没有函数地址,链接时会出现报错。


#include<iostream> using namespace std; 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; } #include<iostream> using namespace std; // 实现⼀个ADD宏函数的常⻅问题 //#define ADD(int a, int b) return a + b; //#define ADD(a, b) a + b; //#define ADD(a, b) (a + b) // 正确的宏实现 #define ADD(a, b) ((a) + (b)) // 为什么不能加分号? // 为什么要加外⾯的括号? // 为什么要加⾥⾯的括号? int main() { int ret = ADD(1, 2); cout << ADD(1, 2) << endl; cout << ADD(1, 2)*5 << endl; int x = 1, y = 2; ADD(x & y, x | y); // -> (x&y+x|y) return 0; } // F.h #include <iostream> using namespace std; inline void f(int i); // F.cpp #include "F.h" void f(int i) { cout << i << endl; } // main.cpp #include "F.h" int main() { // 链接错误:⽆法解析的外部符号 "void __cdecl f(int)" (?f@@YAXH@Z) f(10); return 0; } 8. nullptr
NULL实际上是一个宏,在传统的c语言的头文件(.h)中,可以看到如下代码:
#ifndef NULL #ifdef __cplusplus #define NULL 0 #else #define NULL ((void *)0) #endif #endifC++中NULL可能被定义为字面常量0,或者C中被定义为无类型指针(void*)的常量。不论采取何种定义,在使用空值的指针时,都不可避免的会遇到一些麻烦。本想通过f(NULL)调用指针版本的f(int*)函数,但是由于NULL被定义为0,调用了f(int x),因此与程序的初衷相悖。f((void*)NULL)调用会产生报错。C++11中引入nullptr,nullptr是⼀个特殊的关键字,nullptr是⼀种特殊类型的字面量,它可以转换成任意其他类型的指针类型。使用nullptr定义空指针可以避免类型转换的问题,因为nullptr只能被隐式地转换为指针类型,而不能被转换为整数类型。
#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; }