C++基础
学习 C++,关键是要理解概念,而不应过于深究语言的技术细节。
C++程序结构
#include <iostream> //包含头文件 <iostream>
using namespace std; //定义命名空间 "std"
int main(){ //主函数 main()
cout <<"Hello World!"<< endl; //输出函数 cout,endl表示换号与 "\n"相同
return 0;
}
C++数据类型
| 布尔型 | bool |
| 字符型 | char |
| 整形 | int |
| 长整形 | long |
| 浮点型 | float |
| 双浮点型 | double |
| 无类型 | void |
| 字符串型 | string |
typedef声明
使用typedef可以为已有的类型去一个新的名字
typedef int feet;
feet a;
枚举类型
通常用来定义一种在预估变化内容的变量
enum color [枚举名] {red,blue,yellow,green,white} c [变量名];
c = blue;
cout << c; //输出c的值为:1
enum color [枚举名] {red,blue=5,yellow,green,white} c [变量名];
c = yellow;
cout << c; //输出c的值为:6
类型转换
分为静态转换,动态转换,常量转换,重新解释转换
-
静态转换 (Static_cast)
//静态转换不进行任何运行时类型检查 int i = 10; float b = static_cast<int>(i); //将int类型转换为float类型 -
动态转换 (Dynamic_cast)
//动态转换常用于将父类指针转换为子类指针或引用 class father{ }; class children { } :public father { }; //子类继承父类 father* f = new children; //使用子类实例化父类对象 children* c = dynamic_cast<children*>(f) //将父类指针转换为子类指针 -
常量转换(Const_cast)
//常量转换用于将const类型的对象转换为非const类型的对象 const int i = 10; //定义 int常量 i变量 int& r = const_cast<int&>(i); //常量转换,将const int转换为int -
重新解释转换
//重新解释转换将一个数据类型的值重新解释为另一个数据类型的值,通常用于在不同的数据类型之间进行转换。 int i = 10; float f = reinterpret_cast<float&>(i); // 重新解释将int类型转换为float类型
C++变量类型
| 类型 | 关键字 | 描述 |
|---|---|---|
| 布尔类型 | bool | |
| 整形类型 | int | |
| 长整型类型 | long | |
| 浮点类型 | float | |
| 长浮点类型 | double | |
| 字符类型 | char | |
| 字符串类型 | string | |
| 枚举类型 | enum | |
| 宽字符类型 | wchar_t | |
| 无类型 | void |
通过extern可以在任何地方声明一个变量
posted on 2023-07-06 16:11 Cirrocumuli 阅读(22) 评论(0) 收藏 举报
浙公网安备 33010602011771号