1:从C到C++
- Hello World
#include <iostream>
using namespace std;
int main(){
cout << "Hello World!" << endl;
printf();
}
编译:g++ HelloWorld.cpp -o HelloWorld
执行:./HelloWorld
结果:Hello world!
从HelloWorld.cpp
,看C++
与C
的基本区别:
- 文件后缀名
.cpp
- 头文件
#include <iostream>
- 命名空间
using namespace std
; - 标准输出流
cout
、输出运算符<<
、换行控制器endl
- 编译工具
g++
1.1 源文件后缀
- 头文件后缀名区别
C | C++ |
---|---|
*.h | *.h *.hpp |
- 源文件后缀名区别
C | C++ |
---|---|
*.c | *.cpp *.cc *.cxx |
1.2 引用头文件
C++
头文件使用C
标准库,在C
标准库文件名前加上字母c
,并且省略后缀名.h
,例如:
C | C++ |
---|---|
#include <stdio.h> | #include <iostream> |
#include <stdlib.h> | #include <cstdlib> |
#include <string.h> | #include <cstring> |
#include <math.h> | #include <cmath> |
1.3 函数重载
printf.c
#include <stdio.h>
void printf(){
printf("%s\n","Hello World!");
}
int main(){
printf();
}
printf.cpp
#include <cstdio>
void printf(){`在这里插入代码片`
printf("%s\n","Hello World!");
}
int main(){
printf();
}
- C不支持重载,C++支持重载
1.4 命名空间
- C不支持命名空间,C++支持命名空间
- 命名空间的作用:
避免全局变量、函数、类的命名冲突(因为名字相同而编译失败)。 - 定义命名空间
namespace 空间名 {
// 定义类/函数
}
- 引用命名空间
1、using指令(using directive)
using namespace 空间名;
例如使用标准命名空间std
using namespace std;
2、using声明(using declaration)
using 空间名::标识符;
例如使用标准命名空间std的cout
using std::cout;
- C++命名空间处理方式
#include <iostream>
namespace English{
void printf(){
std::printf("Hello World\n");
}
}
namespace Chinese{
void printf(){
std::printf("你好 世界\n");
}
}
using namespace Chinese;
int main(){
English::printf();
printf();
}
全局命名空间
默认的命名空间,所有名字都在全局命名空间中。
使用方式:直接忽略或者只写::
例如:定义全局函数void printf();
,默认就是在全局命名空间中,调用方式printf()
或者::printf()
。
注:在C++
中,不带.h
后缀的头文件所包含和定义的标识符在std
空间中;
带.h
后缀的头文件所包含和定义的标识符在全局命名空间中,不需要声明使用std
空间
1.5 类型
- 新增基本类型
bool--true/false
- 新增自定义类型
class
1.6 思想
C面向过程,C++面向对象
面向过程:强调如何处理(如何解决)
面向对象:强调执行处理的对象(找谁解决)
思维区别
C:将问题按照过程方式来解决?
C++:将问题抽象为一个对象来解决?
1.7 动态内存
- 动态内存区别:
C | C++ |
---|---|
malloc()/free() | new/delete |
C++
仍然可以使用malloc()/free()
,但是不建议这么做。
实例:
#include <cstdio> // printf()
#include <cstdlib> // malloc() free()
#include <iostream> // cout
using namespace std;
int main(){
int* p = (int*)malloc(sizeof(int));
*p = 100;
printf("%p %d\n",p,*p);
free(p);
p = NULL;
int* q = new int;
*q = 200;
cout << q <<" " << *q << endl;
delete q;
q = NULL;
// malloc()/free()
int* parr = (int*)malloc(sizeof(int)*5);
for(int i=0;i<5;++i){
parr[i] = i;
}
for(int i=0;i<5;++i){
printf("%p %d\n",parr+i,parr[i]);
}
free(parr);
parr = NULL;
// new/delete
int* qarr = new int[5];
for(int i=0;i<5;++i){
qarr[i] = i;
}
for(int i=0;i<5;++i){
cout << qarr+i << " " << qarr[i] << endl;
}
delete [] qarr;
qarr = NULL;
}
1.8 初始化
C++特殊初始化方法
#include <iostream>
using namespace std;
int main(){
int n = 10; // C初始化内置类型
int m(20); // C++初始化变量
int t{20}; // C++11 统一初始化方式
cout << n << " " << m << " " << t<< endl;
}