1.综述C++
1.1. 作者
1.2. 历史背景
1.2.1 应“运”而生?运为何?
1.2.2 C++发展大记事
1.3. 应用领域
1.3.1 系统层软件开发
1.3.2 服务器程序开发
1.3.3 游戏,网络,分布式,云计算
1.4. 内容
C++语言的名字,如果看作C的基本语法,是由操作数C和运算符后++构成。C++是本身这门语言先是C,是完全兼容C,
然后在此基础上++。这个++包含三大部分,C++对C的基础语法的扩展,面向对象(继承、封装、多态),STL等。
1.5. 书籍推荐
C++ Primer C++ 编程思想 C++ Priemer Plus
2.C++对C的扩展
2.1. 类型增强
2.1.1 类型检查更严格
比如,把一个const类型的指针赋给非const类型的指针。C语言中可以通的过,但是在C++中则编不过去。
1 #include <iostream> 2 using namespace std; 3 4 int main(int argc, char *argv[]) 5 { 6 const int a = 100; 7 int b = a; 8 9 const int *pa = &a; 10 int *pb = pa; 11 12 return 0; 13 }
error: cannot initialize a variable of type 'int *' with an lvalue of type 'const int *'
int *pb = pa;
1 #include <stdio.h> 2 3 int main(int argc, char *argv[]) 4 { 5 const int a = 100; 6 int b = a; 7 8 const int *pa = &a; 9 //cannot initialize a variable of type 'int *' with an lvalue of type 'const int *' 10 int *pb = pa; 11 12 return 0; 13 }
warning: initializing 'int *' with an expression of type 'const int *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers]
int *pb = pa;
动态内存分配C/C++区别:
1 #include <iostream> 2 #include <stdlib.h> 3 #include <stdio.h> 4 using namespace std; 5 6 int main() 7 { 8 char *p = malloc(100); //C中可以这样写 9 char *q = (char*)malloc(100); //C中强制类型转换写法 10 11 char *pt = static_cast<char*>(malloc(200)); //C++中强制类型转换写法 12 }
2.1.2 布尔类型(bool)
C语言的逻辑真假用0和非0来表示。而C++中有了具体的类型(bool flag = true/false;),这样的操作,完全可以使用枚举(enum)实现
bool类型在内存中大小等于char类型大小。
2.1.3 真正的枚举(enum)
虽然C中也有枚举,但是在使用的时候,即使赋值不再枚举的范围内,但是依然是可以执行的,但是在C++中,枚举的值必须在枚举的范围内
1 #include <stdio.h> 2 3 int main(void) 4 { 5 enum SEASON{ 6 SPA, SUM, AUT, WIN 7 }; 8 9 enum SEASON s = AUT; 10 enum SEASON r = 100; //这样也可以在C中,在C++这样是不行的 11 return 0; 12 }
2.2. 输入与输出(cin cout)
2.2.1 cin && cout
C中输入典型错误:
1 #include <cstdio> 2 #include <iostream> 3 using namespace std; 4 5 int main() 6 { 7 int a; 8 char c; 9 10 scanf("%d%c", &a, &c); 11 12 return 0; 13 }
这样输入时变量c会读取不到相应的值,因为在输入时我们往往会输入变量a的之后选择空格或者回车符,而变量c接收了空格或者回车符。所以,变量c读取不到对应的值!!!
在C++中,不存在上述问题。(cin >> a >> c;)
注意:
如果定义一个数组,在用这两种输入方式进行输入的时候,都是不安全的,不能保证输入的长度,例如 char name[30]; 用cin>>name;或者使用scanf("%s",name);的时候,如果输入的字符长度超过30个,那么程序就会出错,不过可以使用fgets(name, 30, stdin);这样就指定最多只能接收29个字符(第30个为'