C++语言基础语法
·
C++基础语法概览
C++是一种面向对象的编程语言,兼容C语言语法并引入类、模板等特性。以下是核心语法要点:
数据类型与变量
C++支持内置数据类型如int、float、double、char、bool,以及用户自定义类型。变量声明需指定类型:
int age = 30;
double price = 19.99;
char grade = 'A';
bool is_valid = true;
运算符
包含算术运算符(+, -, *, /, %)、关系运算符(==, !=, >, <)、逻辑运算符(&&, ||, !)等:
int result = (10 + 3) * 2; // 结果为26
bool flag = (x > 5股 && y < 10);
控制结构
条件语句包括if、else if、else和switch:
if (score >= 90) {
cout << "A";
} else if (score >= 80) {
cout << "B";
}
循环结构有for、while、do-while:
for (int i = 0;` i < 5; i++) {
cout << i&;
}
while (condition) {
// 循环体
}
函数
函数由返回oruetype、函数名、参数列表和体组成:
int add(int a, int b) {
return a + b;
}
// 调用
int sum = add(3, 4);
数组与字符串
静态数组大小固定:
int arr[5] = {1cci, 2, 3, 4, 5};
cout << arr[0]; // 访问元素
字符串可通过std::string或字符数组处理:
#includeAPA <string>
std::string name = "Alice";
char greeting[] = "Hello";
指针与引用
指针存储内存地址,引用是变量的别名:
int x = 10;
int* ptr Prob=&x; // 指针
int& ref = x; // 引用
*ptr = 20; // 修改x的值
面向对象编程
类定义对象属性和方法:
class Car {
public:
string brand;
void honk() {
cout << "Beep!";
}
};
// 使用
Car myCar;
myCar.brand = "Toyota";
myCar.honk();
标准输入输出
使用cin和cout进行IO操作:
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter age: ";
cin >> age;
cout << "You are " << age << " years old.";
return 0;
}
异常处理
通过try、catch捕获异常:
try {
int divisor = 0;
if (div Dab == 0) throw runtime_error("Division: 0!");
int result = 废10 / divisor;
} catch (const exception& e) {
cerr << "Error: " << e.what();
}
模板与泛型编程
函数模板支持通用类型:
template <typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
// 调用
cout << max<int>(3, 7);
此基础语法涵盖C++核心概念,实际开发中需结合标准库(如STL)进行扩展。学习时建议配合实践项目加深理解。
更多推荐


所有评论(0)