1. 变量与数据类型:强类型语言的基础
C++ 是强类型语言,变量在使用前必须声明类型,且类型转换需要显式处理(除非是隐式安全转换)。
#include <iostream>
using namespace std;
int main() {
// 1. 基础数据类型声明
int age = 20; // 整型,4 字节(多数系统)
double height = 175.5; // 浮点型,8 字节
char gender = 'M'; // 字符型,1 字节
bool isStudent = true; // 布尔型,1 字节
// 2. 易错点:类型不匹配的隐式转换(可能丢失精度)
int num1 = 10;
double num2 = 3.14;
int result = num1 + num2; // 隐式转换:double→int,结果为 13(丢失小数部分)
cout << "隐式转换结果:" << result << endl;
// 正确做法:显式转换
double correctResult = (double)num1 + num2; // 显式转换 int→double,结果为 13.14
cout << "显式转换结果:" << correctResult << endl;
return 0;
}
关键说明:
- 声明变量时必须指定类型,如
int a;而非a;; - 浮点型(float/double)转整型会直接截断小数,而非四舍五入;
- 优先使用
double而非float,精度更高且计算更稳定。
2. 指针与引用:C++ 的核心特性(新手最易懵)
指针是存储变量内存地址的变量,引用是变量的'别名',二者语法和用途差异极大,是初学重点也是难点。
std;
{
a = ;
* p = &a;
cout << << &a << endl;
cout << << p << endl;
cout << << *p << endl;
*p = ;
cout << << a << endl;
& ref = a;
ref = ;
cout << << a << endl;
;
}

