案例:输出Hello World
- 源代码:HelloWorld.cpp
#include <iostream>
using namespace std;
int main(){
cout<<"Hello,World."<<endl;
}
从helloworld看到的C和C++的区别:
- 文件后缀名“.c和.cpp”
- 头文件
#include <iostream>
- 命名空间
using namespace std;
- 标准输出’cout’,输出运算符’<<’,换行’endl’
- 编译工具:g++
没有需要安装:yum install gcc-c++ -y
引用头文件
c++头文件使用C标准库,在C标准库文件名前字母’C’,并且省略后缀名’.h’,例如:
‘#include
函数重载(overload)
- printf.c
#include <cstdio>
void printf()
{
printf("hello world\n");
}
int main()
{
printf();
}
函数重载:函数名相同只有参数(个数或者类型)不同。
命名空间
- scope.c
#include <cstdio>
namespace scope1 {
void test(){
printf("this is test\n");
}
}
namespace scope2 {
void test(){
printf("this is another test\n");
}
}
int main(){
scope1::test();
scope2::test();
}
命名空间的作用:避免全局变量,函数,类的命名冲突。
类型
- 新增基本类型‘bool’ –‘true’/’false’
- 新增自定义类型class
思想
何为面向过程?何为面向对象?
- 面向过程:强调如何处理,通常是自下而上。
- 面向对象:强调如何处理的对象,通常是自上而下。
面向过程与面向对象:厨师和老板
动态内存
dynamic_mem.cpp
#include <iostream>
int main(){
int* num = new int;
*num = 100;
std::cout << *num << std::endl;
delete num;
}
new 和delete都是关键字,用于申请/释放内存。