C++关键字
asm | do | if | return | try | continue |
auto | double | inline | short | typedef | for |
bool | dynamic_cast | int | signed | typeid | public |
break | else | long | sizeof | typename | throw |
case | enum | mutable | static | union | wchar_t |
catch | explicit | namespace | static_cast | unsigned | default |
char | export | new | struct | using | friend |
class | extern | operator | switch | virtual | register |
const | false | private | template | void | true |
const_cast | float | protected | this | volatile | while |
delete | goto | reinterpret_cast |
输入输出
代码演示
#include <iostream>
using namespace std;
int main(){
int year, month, day;
cout << "Please input the date: " << endl;
cin >> year >> month >> day;
cout << "hello, world! " << year << "-" << month << "-" << day << endl;
return 0;
}
运行结果
[sss@aliyun C++]$ ./a.out
Please input the date:
2019 04 23
hello, world! 2019-4-23
说明
使用cout标准输出(控制台)和cin标准输入(键盘)时,必须包含头文件以及std标准命名空间。
使用C++输入输出更方便,不许增加数据格式控制,如:%d,%f等。
命名空间
命名空间是ANSI C++引入的可以由用户命名的作用域,用来处理程序中常见的同名冲突。所谓命名空间,实际上就是一个由程序设计者命名的内存区域。程序设计者可以根据需要指定一些有名字的空间域,把一些全局实体分别放在各个命名空间中,从而与其他全局实体分割开来。
命名空间的定义
普通命名空间
namespace sss{
int meng = 521;
int sss_0916(){
printf("hello, world!\n");
}
}
命名空间的嵌套定义
namespace sss_0916{
int meng = 916;
namespace sss{
int Zmeng = 1021;
int zMeng(){
printf("hello, world!\n");
}
}
}
同一工程中的相同名称的命名空间
namespace sss{
int meng = 521;
int sss_0916(){
printf("hello, world!\n");
}
}
namespace sss{
int zhang = 10;
}
同一个工程中允许存在多个相同名称的命名空间,编译器最后会合成同一个命名空间。
注意:一个命名空间就是定义了一个新的作用域,命名空间中的所有内容都局限于该命名空间中。
命名空间的使用
三种使用方式
命名空间名称及作用域限定符
#include <iostream>
int main(){
std::cout << "hello, world!" << std::endl;
return 0;
}
using将命名空间中的成员导入
#include <iostream>
using std::cout;
using std::endl;
int main{
cout << "hello, world!" << endl;
return 0;
}
using namespace 命名空间
#include <iostream>
using namespace std;
int main(){
cout << "hello, world!" << endl;
return 0;
}
代码演示
#include <iostream>
using namespace std;
namespace sss{
int meng = 521;
int _sss0916(){
cout << "hello, world!" << endl;
}
}
namespace sss{
int zhang = 10;
}
namespace sss_0916{
int meng = 916;
namespace sss0916{
int Zmeng = 1021;
int zMeng(){
cout << "hello, world!" << endl;
}
}
}
using namespace sss;
using sss_0916::sss0916::zMeng;
int main(){
cout << "meng: " << meng << endl;
_sss0916();
cout << "zhang: " << zhang << endl;
zMeng();
return 0;
}
运行结果
[sss@aliyun namespace]$ ./a.out
meng: 521
hello, world!
zhang: 10
hello, world!
参数缺省
参数是声明或定义函数时为函数的参数指定一个默认值。在调用该函数时,如果没有指定实参则采用该默认值,否则使用指定的实参。
缺省参数分类
全缺省
void allDefault(int a = 1, double b = 3.14){
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
半缺省
void partDefault(int a, double b = 5.21){
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
代码演示
#include <iostream>
using namespace std;
void allDefault(int a = 1, double b = 3.14){
cout << "all default!" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
void partDefault(int a, double b = 5.21){
cout << endl << "part default!" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
int main(){
allDefault();
partDefault(2);
return 0;
}
运行结果
[sss@aliyun default]$ ./a.out
all default!
a = 1
b = 3.14
part default!
a = 2
b = 5.21
总结
半缺省参数必须从由往左依次来给出,不能隔着给。缺省参数不能在函数声明和定义中同时出现。缺省值必须是常量或全局变量。C语言不支持(编译器不支持)。
函数重载
C++中允许同一作用域中定义多个同名函数。这就是函数的重载。即对一个函数名重新赋予它新的含义,使一个函数名可以多用。所谓重载,其实就是“一物多用”。这些同名函数的形参列表(参数个数、类型或顺序)必须不同,常用来处理实现功能类似数据类型不同的问题。
代码演示
#include <iostream>
using namespace std;
int add(int a, int b){
cout << "int: a + b = " << a + b << endl;
}
double add(double a, double b){
cout << "double: a + b = " << a + b << endl;
}
long add(long a, long b){
cout << "long: a + b = " << a + b << endl;
}
int main(){
add(1, 2);
add(1.1, 2.2);
add(1L, 2L);
return 0;
}
运行结果
[sss@aliyun reload]$ ./a.out
int: a + b = 3
double: a + b = 3.3
long: a + b = 3
注意,下述示例都不属于函数重载
示例一
int add(int a, int b){
return a + b;
}
int add(int b, int a){
return b + a;
}
示例二
int add(int a, int b){
return a + b;
}
long add(int a, int b){
return a + b;
}
示例三
int add(int a, int b){
return a + b;
}
int add(int a = 1, b = 2){
return a + b;
}
为什么C语言不支持函数重载,而C++可以?
C语言中函数重载代码测试
#include <stdio.h>
#include <stdlib.h>
int test(int a, int b);
int test(int a, char b);
int test(char a, int b);
int main()
{
test(1, 2);
test(1, '2');
test('1', 2);
system("pause");
return 0;
}
运行结果
1>源.obj : error LNK2019: 无法解析的外部符号 _test,该符号在函数 _main 中被引用
1>d:\backup\documents\visual studio 2013\Projects\Project2\Debug\Project2.exe : fatal error LNK1120: 1 个无法解析的外部命令
C++中函数重载代码测试
#include <iostream>
using namespace std;
int test(int a, int b);
int test(int a, char b);
int test(char a, int b);
int main()
{
test(1, 2);
test(1, '2');
test('1', 2);
system("pause");
return 0;
}
运行结果
1>源.obj : error LNK2019: 无法解析的外部符号 "int __cdecl test(int,int)" (?test@@YAHHH@Z),该符号在函数 _main 中被引用
1>源.obj : error LNK2019: 无法解析的外部符号 "int __cdecl test(int,char)" (?test@@YAHHD@Z),该符号在函数 _main 中被引用
1>源.obj : error LNK2019: 无法解析的外部符号 "int __cdecl test(char,int)" (?test@@YAHDH@Z),该符号在函数 _main 中被引用
1>d:\backup\documents\visual studio 2013\Projects\Project2\Debug\Project2.exe : fatal error LNK1120: 3 个无法解析的外部命令
总结
- C编译器眼中的函数名:
_test
。 - C++编译器眼中的函数名:
"int __cdecl test(char,int)" (?test@@YAHDH@Z)
从上述可以看出,C编译器和C++编译器对函数名的修饰是不同的。
名字修饰
在C/C++中,一个程序要运行起来,需要经历以下几个阶段:预处理、编译、汇编、链接。
Name Mangling是一种在编译过程中,将函数、变量的名称重新改编的机制,简单来说就是编译器为了区分各个函数,将函数通过某种算法,重新修饰为一个全局唯一的名称。
C语言的名字修饰规则非常简单,只是在函数名字前面添加了下划线。比如,前面演示的:无法解析的外部符号 _test
。
前面该函数只给了声明没有给定义,因此在链接时就会报错,从报错结果可以看出,C语言只是简单的在函数名前添加下划线。因此当工程中存在相同函数名的函数时,就会产生冲突。
由于C++要支持重载,命名空间等,使得其修饰规则比较复杂,不同编译器在底层的实现方式可能都有差异。由前面演示结果:无法解析的外部符号 "int __cdecl test(int,int)" (?test@@YAHHH@Z)
。可以看出,编译器实际在底层使用的不是test名字,而是被重新修饰过的一个比较复杂的名字,被重新修饰后的名字包含了:函数的名字以及参数类型。这就是为什么函数重载中几个同名函数要求其参数列表不同的原因。只要参数列表不同,编译器在编译时通过对函数名字进行重新修饰,将参数类型包含在最终的名字中,就可保证名字在底层的全局唯一性。
函数名 | 修饰后名称 |
---|---|
int func(int) | ?func@@YAHH@Z |
float func(float) | ?func@@YAMM@Z |
int C::func(int) | ?func@C@@AAEHH@Z |
int C::C2::func(int) | ?func@C2@C@@AAEHH@Z |
int N::func(int) | ?func@N@@YAHH@Z |
int N::C::func(int) | ?func@C@N@@AAEHH@Z |
我们以int N::C::func(int)这个函数名来猜测VC++的名字修饰规则(大概了解即可)。修饰后名字由“?”开头,接着是函数名由“@”符号结尾的函数名;后面跟着由“@”结尾的类名“C”和名称空间“N”,再一个“@”表示函数的名称空间结束;第一个“A”表示函数调用类型为“__cdecl”,接着是函数的参数类型及返回值,由“@”结束,最后由“Z”结尾。可以看到函数名、参数的类型和名称空间都被加入了修饰后名称,这样编译器和链接器就可以区别同名但不同参数类型或命名空间的函数,而不会导致link的时候函数多重定义。
extern “C”
有时候C++工程中可能需要将某些函数按照C的风格来编译,在函数前加extern “C”,意思是告诉编译器,将该函数按照C语言规则来编译。
extern "C" int add(int a, int b);
引用
引用不是新定义一个变量,而是给已存在变量取了一个别名,编译器不会为引用变量开辟内存空间,它和它引用的变量共用同一块内存空间。
类型& 引用变量名(对象名) = 引用实体。
代码演示
#include <iostream>
using namespace std;
int main(){
int a = 0;
int& ra = a;
cout << "&a: " << &a << endl;
cout << "&ra: " << &ra << endl;
return 0;
}
运行结果
[sss@aliyun quote]$ ./a.out
&a: 0x7ffe59fc47d4
&ra: 0x7ffe59fc47d4
引用特性
- 引用类型必须和引用实体是同种类型的。
- 引用在定义时必须初始化。
- 一个变量可以有多个引用。
- 引用一旦引用一个实体,再不能引用其他实体。
常引用
const int a = 10;
const int& ra = a;
const double b = 3.14;
const double& rb = b;
使用场景
做参数
代码演示
#include <iostream>
using namespace std;
void swap(int& a, int& b){
int temp = a;
a = b;
b = temp;
}
int main(){
int a = 10;
int b = 20;
cout << "before swap: a = " << a << ", b = " << b << endl;
swap(a, b);
cout << "after swap: a = " << a << ", b = " << b << endl;
return 0;
}
运行结果
[sss@aliyun quote]$ ./a.out
before swap: a = 10, b = 20
after swap: a = 20, b = 10
做返回值
代码演示
#include <iostream>
using namespace std;
int& add(int a, int b){
int sum = a + b;
return sum;
}
int main(){
int& sum = add(1, 2);
cout << "sum: " << sum << end;
return 0;
}
运行结果
[sss@aliyun quote]$ !g++
g++ quote.cpp
quote.cpp: In function ‘int& add(int, int)’:
quote.cpp:5:6: warning: reference to local variable ‘sum’ returned [-Wreturn-local-addr]
int sum = a + b;
^
quote.cpp: In function ‘int main()’:
quote.cpp:13:28: error: ‘end’ was not declared in this scope
cout << "sum: " << sum << end;
注意:如果函数返回时,离开函数作用域后,其栈上空间已经还给系统,因此不能用栈上的空间作为引用类型返回。如果以引用类型返回,返回值的生命周期必须不受函数的限制(即比函数声明周期长)。
传值、传引用效率对比
以值作为参数或者返回值类型,在传参和返回期间,函数不会直接传递实参或者将变量本身直接返回,而是传递实参或者返回变量的一份临时的拷贝,因此用值作为参数或者返回值类型,效率是非常低下的,尤其是当参数或者返回值类型非常大时,效率就更低。
代码演示
#include <iostream>
#include <ctime>
using namespace std;
struct Sss{
int a[10000];
};
void valTest(Sss s){
}
void refTest(Sss& s){
}
void testValAndRef(){
Sss s;
int i;
clock_t start1 = clock();
for(i = 0; i < 10000; ++i){
valTest(s);
}
clock_t end1 = clock();
clock_t start2 = clock();
for(i = 0; i < 10000; ++i){
refTest(s);
}
clock_t end2 = clock();
cout << "val time: " << end1 - start1 << endl;
cout << "ref time: " << end2 - start2 << endl;
}
int main(){
int i;
for(i = 0; i < 10; ++i){
testValAndRef();
}
return 0;
}
运行结果
[sss@aliyun quote]$ ./a.out
val time: 10000
ref time: 0
val time: 20000
ref time: 0
val time: 10000
ref time: 0
val time: 10000
ref time: 0
val time: 20000
ref time: 0
val time: 10000
ref time: 0
val time: 10000
ref time: 0
val time: 20000
ref time: 0
val time: 10000
ref time: 0
val time: 20000
ref time: 0
值和引用作为返回值类型的性能对比
代码演示
#include <iostream>
#include <ctime>
using namespace std;
struct Sss{
int a[10000];
};
Sss s;
Sss valTest(){
return s;
}
Sss& refTest(){
return s;
}
void testReturnOfValAndRef(){
int i;
clock_t start1 = clock();
for(i = 0; i < 10000; ++i){
valTest();
}
clock_t end1 = clock();
clock_t start2 = clock();
for(i = 0; i < 10000; ++i){
refTest();
}
clock_t end2 = clock();
cout << "val time: " << end1 - start1 << endl;
cout << "ref time: " << end2 - start2 << endl;
}
int main(){
int i;
for(i = 0; i < 10; ++i){
testReturnOfValAndRef();
}
return 0;
}
运行结果
[sss@aliyun quote]$ ./a.out
val time: 10000
ref time: 0
val time: 10000
ref time: 0
val time: 20000
ref time: 0
val time: 10000
ref time: 0
val time: 10000
ref time: 0
val time: 20000
ref time: 0
val time: 10000
ref time: 0
val time: 20000
ref time: 0
val time: 10000
ref time: 0
val time: 10000
ref time: 0
总结
通过上述代码的比较,发现值和引用在作为传参以及返回值类型上效率相差很大。
引用和指针
在语法概念上引用就是一个别名,没有独立空间,和其引用实体共用同一块空间。在底层实际是有空间的,因为引用是按照指针方式来实现的。
引用和指针的汇编代码对比
引用
int a = 10;
mov dword ptr [a], 0Ah
int& ra = a;
lea eax, [a]
mov dword ptr [ra], eax
ra = 20;
mov eax, dword ptr [ra]
mov dword ptr [eax], 14h
指针
int a = 10;
mov dword ptr [a], 0Ah
int* pa = &a;
lea eax, [a]
mov dword ptr [pa], eax
*pa = 20;
mov eax, dword ptr [pa]
mov dword ptr [eax], 14h
引用和指针区别
- 引用在定义时必须初始化,指针没有要求。
- 引用在初始化时引用一个实体后,就不能再引用其他实体,而指针可以在任何时候指向任何一个同类型实体。
- 没有NULL引用,但有NULL指针。
- 在sizeof中含义不同:引用结果为引用类型的大小,但指针始终是地址空间所占字节个数。
- 引用自加即引用实体增加1,指针自加即指针向后偏移一个类型的大小。
- 有多级指针,但是没有多级引用。
- 访问实体方式不同,指针需要显式解引用,引用编译器自己处理。
- 引用比指针用起来相对更安全。
内联函数
以inline修饰的函数叫做内联函数,编译时C++编译器会在调用内联函数的地方展开,没有函数压栈的开销,内联函数提升程序运行的效率。
如果在上述函数前增加inline关键字将其改成内联函数,在编译期间编译器会用函数体替换函数的调用。
查看方式
在release模式下,查看编译器生成的汇编代码中是否存在call add。
在debug模式下,需要对编译器进行设置,否则不会展开(因为debug模式下,编译器默认不会对代码进行优化,一下给出vs2013的设置方式)。
特性
- inline是一种以空间换时间的做法,省去调用函数额外开销。所以代码很长或者有循环/递归的函数不适宜使用内联函数。
- inline对于编译器而言只是一个建议,编译器会自动优化,如果定义为inline的函数体内有循环/递归等等,编译器优化时会忽略掉内联。
- inline不建议声明和定义分离,分离会导致链接错误。因为inline被展开,就没有函数地址了,链接就会找不到。
宏的优缺点
优点
- 增强代码的复用性。
- 提高性能。
缺点
- 不方便调试宏(预编译阶段进行了替换)。
- 导致代码可读性差。
- 没有类型安全的检查。
C++有哪些技术替代宏
- 宏常量用const来替换。
#define N 10
const int n = 10;
- 宏函数用内联函数替换。
auto关键字
在早期C/C++中auto的含义是:使用auto修饰的变量,是具有自动存储器的局部变量,但遗憾的是一直没有人去使用它,为什么呢?
C++11中,标准委员会赋予了auto全新的含义即:auto不再是一个存储类型指示符,而是作为一个新的类型指示符来指示编译器,auto声明的变量必须由编译器在编译时期推导而得。
代码演示
#include <iostream>
#include <typeinfo>
using namespace std;
int autoTest(){
return 10;
}
int main(){
int a = 1;
auto b = a;
auto c = 'a';
auto d = autoTest();
cout << typeid(b).name() << endl;
cout << typeid(c).name() << endl;
cout << typeid(d).name() << endl;
return 0;
}
运行结果
[sss@aliyun auto]$ !g++
g++ auto.cpp -std=c++11
[sss@aliyun auto]$ ./a.out
i
c
i
注意:使用auto定义变量时必须对其进行初始化,在编译阶段编译器需要根据初始化表达式来推导auto的实际类型。因此auto并非是一种“类型”的声明,而是一个类型声明时的“占位符”,编译器在编译期间会将auto替换为变量实际的类型。
auto使用细则
auto与指针和引用结合起来使用
用auto声明指针类型时,用auto和auto*没有区别,但用auto声明引用类型时必须加&。
代码演示
#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
int x = 10;
auto a = &x;
auto* b = &x;
auto& c = x;
cout << typeid(a).name() << endl;
cout << typeid(b).name() << endl;
cout << typeid(c).name() << endl;
return 0;
}
运行结果
[sss@aliyun auto]$ ./a.out
Pi
Pi
i
同一行定义多个变量
当在同一行声明多个变量时,这些变量必须是相同的类型,否则编译器将会报错,因为编译器实际只对第一个类型进行推导,然后用推导出来的类型定义其他变量。
代码演示
#include <iostream>
using namespace std;
int main(){
auto a = 1, b = 2;
auto c = 3, d = 4.0;
return 0;
}
运行结果
[sss@aliyun auto]$ !g++
g++ auto.cpp -std=c++11
auto.cpp: In function ‘int main()’:
auto.cpp:6:18: error: inconsistent deduction for ‘auto’: ‘int’ and then ‘double’
auto c = 3, d = 4.0;
auto不能推导的场景
- auto不能作为函数的参数。
void autoTest(auto a){
}
编译器无法对a的实际类型进行推导。
- auto不能直接用来声明数组。
void autoTest(){
int a[] = {1, 2, 3};
auto b[] = {4, 5, 6};
}
- 为了避免与C++98中的auto发生混淆,C++11保留了auto作为类型指示符的用法。
- auto在实际中最常见的优势用法就是跟C++11提供的新式for循环,还有lambda表达式等进行配合。
- auto不能定义类的非静态成员变量。
- 实例化模板时不能使用auto作为模板参数。
auto的弊端
可读性差,写的人很爽,读的人蛋疼。
基于范围的for循环(C++11)
范围for循环的语法
C++98中遍历数组
代码演示
#include <iostream>
using namespace std;
int main(){
int arr[] = {
1, 2, 3, 4, 5, 6, 7
};
for(int i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i){
arr[i] *= 2;
}
for(int* p = arr; p < arr + sizeof(arr) / sizeof(arr[0]); ++p){
cout << *p << " ";
}
cout << endl;
return 0;
}
运行结果
[sss@aliyun for]$ ./a.out
2 4 6 8 10 12 14
C++11
对于一个有范围的集合而言,由程序猿来说明循环的范围是多余的,有时候还会容易犯错误。因此C++11中引入了基于范围的for循环。for循环后的括号由冒号" : "分为两部分:第一部分是范围内用于迭代的变量,第二部分则表示被迭代的范围。
代码演示
#include <iostream>
using namespace std;
int main(){
int arr[] = {
1, 2, 3, 4, 5, 6, 7
};
for(auto& e : arr){
e *= 2;
}
for(auto e : arr){
cout << e << " ";
}
cout << endl;
return 0;
}
运行结果
[sss@aliyun for]$ ./a.out
2 4 6 8 10 12 14
注意:与普通循环类似,可以用continue来结束本次循环,也可以用break来跳出整个循环。
范围for的使用条件
for循环迭代的范围必须是确定的
对于数组而言,就是数组中第一个元素和最后一个元素的范围;对于类而言,应该提供begin和end的方法,begin和end就是for循环迭代的范围。
迭代的对象要实现++和==操作
指针控制nullptr(C++11)
C++98中的指针空值
在良好的C/C++编程习惯中,声明一个变量时最好给该变量一个合适的初值,否则可能出现不可预料的错误,比如未初始化指针。如果一个指针没有合法的指向,我们基本就是按照如下方式对其进行初始化。
void ptrTest(){
int* p1 = NULL;
int* p2 = 0;
}
NULL实际上是一个宏,在传统的C头文件(stddef.h)中,可以看到如下代码:
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void*)0)
#endif
#endif
可以看到,NULL可能被定义为字面常量0,或者被定义为无类型指针(void*)的常量。不论采取何种定义,在使用空值的指针时,都不可避免的会遇到一些麻烦,比如:
#include <iostream>
#include <cstdlib>
using namespace std;
void ptrTest(int){
cout << "f(int)" << endl;
}
void ptrTest(int*){
cout << "f(int*)" << endl;
}
int main(){
ptrTest(0);
ptrTest(NULL);
ptrTest((int*)NULL);
return 0;
}
编译报错:
[sss@aliyun C++]$ !g++
g++ ptr_test.cpp
ptr_test.cpp: In function ‘int main()’:
ptr_test.cpp:15:14: error: call of overloaded ‘ptrTest(NULL)’ is ambiguous
ptrTest(NULL);
程序本意是向通过ptrTest(NULL)调用指针版本的f(int*)函数,但是由于NULL有两个值,所以报错。
在C++98中,字面值常量0既可以是一个整型数字,也可以是无类型的指针(void*)常量,但是编译器默认情况下将其看成是一个整型常量,如果要将其按照指针方式来使用,必须对其进行强转(int*)0.
nullptr和nullptr_t
为了考虑兼容性,C++11并没有消除常量0的二义性,C++11给出了全新的nullptr表示空值指针。C++11为什么不在NULL的基础上进行扩展,这是因为NULL以前就是一个宏,而且不同的编译器厂商对于NULL的实现可能不太相同,而且直接扩展NULL,可能会影响以前旧的程序。因此:为了避免混淆,C++11提供了nullptr,即:nullptr代表一个指针空值常量。nullptr是有类型的,其类型为nullptr_t,仅仅可以被隐式转化为指针类型,nullptr_t被定义在头文件中:
typedef decltype(nullptr) nullptr_t;
注意:
- 在使用nullptr表示指针空值时,不需要包含头文件,因为nullptr是C++11作为新关键字引入的。
- 在C++11中,sizeof(nullptr)与sizeof((void*)0)所占的字节数相同。
为了提高代码的健壮性,在后续表示指针空值时建议最好使用nullptr。