云计算百科
云计算领域专业知识百科平台

C++ 简述基础语法教程(入门级)

1. 程序结构

所有C++程序都从main()函数开始执行。基本结构如下:

#include <iostream> // 引入输入输出功能
using namespace std; // 使用标准命名空间(简化代码)

int main() {
cout << "Hello, C++!" << endl; // 输出语句
return 0; // 程序正常结束
}

‌关键点‌:

  • #include <iostream>:引入输入输出库
  • using namespace std;:避免每次写std::前缀(大型项目慎用)
  • return 0;:表示程序成功结束(可省略,C++11起默认返回0)

2. 变量与数据类型

2.1 基本数据类型

类型用途示例
int 整数 int age = 25;
double 小数(双精度) double price = 3.99;
char 单个字符 char grade = 'A';
string 字符串(需#include <string>) string name = "Alice";
bool 真/假值 bool isStudent = true;

2.2 变量声明

int num = 10; // 整数
double pi = 3.14; // 小数
string text = "Hi";// 字符串

3. 输入与输出

3.1 输出(cout)

cout << "姓名: " << name << endl; // 输出变量并换行
cout << "年龄: " << age << "岁" << endl;

3.2 输入(cin)

int age;
string name;
cout << "请输入姓名和年龄: ";
cin >> name >> age; // 空格分隔输入

4. 运算符

4.1 算术运算符

int a = 10, b = 3;
cout << a + b << endl; // 13
cout << a – b << endl; // 7
cout << a * b << endl; // 30
cout << a / b << endl; // 3(整数除法)
cout << a % b << endl; // 1(取余)

4.2 赋值运算符

int x = 5;
x += 3; // 等价于 x = x + 3;
cout << x << endl; // 8

5. 控制结构

5.1 条件语句(if-else)

int score = 85;
if (score >= 90) {
cout << "优秀";
} else if (score >= 60) {
cout << "及格";
} else {
cout << "不及格";
}

for 循环

for (int i = 0; i < 5; i++) {
cout << i << " ";
}
// 输出: 0 1 2 3 4

while 循环

int count = 0;
while (count < 3) {
cout << count << " ";
count++;
}
// 输出: 0 1 2

6. 函数

6.1 定义与调用

// 函数定义
int add(int a, int b) {
return a + b;
}

// 主函数调用
int main() {
int sum = add(3, 5);
cout << sum << endl; // 8
return 0;
}

6.2 默认参数

void greet(string name = "Guest") {
cout << "Hello, " << name << "!" << endl;
}

greet("Alice"); // 输出: Hello, Alice!
greet(); // 输出: Hello, Guest!

学习建议

  • 从简单程序开始,逐步增加复杂度
  • 使用在线编译器(如Compiler Explorer)快速验证代码
  • 遇到错误时,仔细阅读编译器提示
  • 每天练习30分钟,比一次性长时间学习更有效
  • 赞(0)
    未经允许不得转载:网硕互联帮助中心 » C++ 简述基础语法教程(入门级)
    分享到: 更多 (0)

    评论 抢沙发

    评论前必须登录!