C++基础语法重点知识
·
C++基础语法重点知识
变量与数据类型
C++支持多种数据类型,包括整型(int)、浮点型(float/double)、字符型(char)和布尔型(bool)。变量声明时需要指定类型,例如:
int age = 25;
double price = 99.99;
char grade = 'A';
bool is_valid = true;
运算符
C++包含算术运算符(+、-、*、/、%)、关系运算符(==、!=、>、<)、逻辑运算符(&&、||、!)和赋值运算符(=、+=、-=)。例如:
int result = 10 + 5 * 2; // 结果为20
bool is_true = (10 > 5) && (3 != 2); // 结果为true
控制结构
C++支持条件语句(if-else、switch)和循环语句(for、while、do-while)。例如:
if (score >= 60) {
cout << "Pass";
} else {
cout << "Fail";
}
for (int i = 0; i < 5; i++) {
cout << i << endl;
}
函数
函数用于封装可重用的代码块,包含返回类型、函数名、参数列表和函数体。例如:
int add(int a, int b) {
return a + b;
}
数组与字符串
数组用于存储相同类型的元素,字符串可以用字符数组或string类表示。例如:
int numbers[5] = {1, 2, 3, 4, 5};
string name = "Alice";
指针与引用
指针存储内存地址,引用是变量的别名。例如:
int num = 10;
int *ptr = #
int &ref = num;
面向对象基础
C++支持类和对象,包含封装、继承和多态特性。例如:
class Person {
private:
string name;
public:
void setName(string n) {
name = n;
}
string getName() {
return name;
}
};
标准输入输出
使用cin和cout进行输入输出操作,需要包含<iostream>头文件。例如:
int age;
cout << "Enter your age: ";
cin >> age;
cout << "You are " << age << " years old.";
动态内存管理
使用new和delete运算符动态分配和释放内存。例如:
int *arr = new int[10];
delete[] arr;
异常处理
C++通过try-catch块处理异常。例如:
try {
if (divisor == 0) {
throw "Division by zero!";
}
} catch (const char* msg) {
cout << "Error: " << msg;
}
更多推荐



所有评论(0)