C++ 简介

什么是 C++?

C++ 是由 Bjarne Stroustrup 于 1979 年在贝尔实验室开始开发的通用编程语言。它是 C 编程语言的扩展,具有面向对象编程功能。

高性能

C++ 编译为机器码,提供出色的运行时性能

面向对象

支持类、对象、继承和多态

内存控制

通过指针和引用进行直接内存管理

标准库

丰富的 STL,包含容器、算法和实用工具

你的第一个 C++ 程序

让我们从传统的"Hello, World!"程序开始:

Hello World 程序

#include <iostream>
using namespace std;

int main() {
    cout << "Hello, World!" << endl;
    return 0;
}

代码解释:

  • #include <iostream> - 包含输入/输出流库
  • using namespace std; - 允许我们使用标准库函数而无需 std:: 前缀
  • int main() - 程序执行开始的主函数
  • cout - 用于向控制台打印的字符输出流
  • return 0; - 表示程序成功终止

基本输入和输出

C++ 使用流进行输入和输出操作:

输入输出示例

#include <iostream>
#include <string>
using namespace std;

int main() {
    string name;
    int age;
    
    // Output
    cout << "Enter your name: ";
    
    // Input
    getline(cin, name);  // Read entire line including spaces
    
    cout << "Enter your age: ";
    cin >> age;  // Read integer
    
    // Output with variables
    cout << "Hello, " << name << "!" << endl;
    cout << "You are " << age << " years old." << endl;
    
    return 0;
}

注释

注释有助于记录代码,编译器会忽略它们:

注释类型

#include <iostream>
using namespace std;

/*
 * This is a multi-line comment
 * Used for longer explanations
 * Author: Your Name
 * Date: Today
 */

int main() {
    // This is a single-line comment
    cout << "Hello, World!" << endl;  // Comment at end of line
    
    /* 
       Multi-line comment can also be 
       used inline like this 
    */
    cout << "Learning C++!" << endl;
    
    return 0;  // Program ends successfully
}

编译过程

C++ 是编译型语言。以下是编译和运行程序的方法:

步骤 1:编写代码

创建一个 .cpp 文件(例如:hello.cpp)

步骤 2:编译

使用 g++ 编译器:g++ -o hello hello.cpp

步骤 3:运行

执行:./hello(Linux/Mac)或 hello.exe(Windows)

常见初学者错误

缺少分号

C++ 中的每个语句都必须以分号 ; 结尾

大小写敏感

C++ 区分大小写:cout ≠ Cout ≠ COUT

缺少头文件

不要忘记 #include 必要的头文件

括号不匹配

每个开括号 { 都必须有对应的闭括号 }