C++的基本语法结构有哪些?
·
变量与数据类型
C++支持多种数据类型,包括整型(int、short、long)、浮点型(float、double)、字符型(char)和布尔型(bool)。变量声明需指定类型,例如:
int age = 25;
double price = 19.99;
char grade = 'A';
bool is_valid = true;
运算符
C++包含算术运算符(+、-、*、/、%)、关系运算符(==、!=、>、<)、逻辑运算符(&&、||、!)和赋值运算符(=、+=)。例如:
int result = (10 + 5) * 2; // 结果为30
bool is_equal = (result == 30);
控制结构
条件语句包括if-else和switch,循环语句有for、while和do-while。示例:
if (age >= 18) {
cout << "Adult";
} else {
cout << "Minor";
}
for (int i = 0; i < 5; i++) {
cout << i << endl;
}
函数
函数由返回类型、函数名、参数列表和函数体组成。例如:
int add(int a, int b) {
return a + b;
}
调用函数时传递实际参数:
int sum = add(3, 4); // sum值为7
数组与字符串
数组是相同类型元素的集合,字符串可通过字符数组或string类实现。示例:
int numbers[3] = {1, 2, 3};
string greeting = "Hello";
指针与引用
指针存储内存地址,引用是变量的别名。例如:
int x = 10;
int* ptr = &x; // ptr指向x的地址
int& ref = x; // ref是x的引用
类与对象
类定义数据成员和成员函数,对象是类的实例。示例:
class Person {
public:
string name;
void introduce() {
cout << "Name: " << name;
}
};
Person p1;
p1.name = "Alice";
p1.introduce();
输入输出
使用cin和cout进行标准输入输出,需包含头文件<iostream>。示例:
int num;
cout << "Enter a number: ";
cin >> num;
cout << "You entered: " << num;
注释
单行注释用//,多行注释用/* ... */。例如:
// 这是单行注释
/*
这是
多行注释
*/
学好每一个知识点,每天进步一点点!
更多推荐


所有评论(0)