一、数据类型和变量声明
C++是一种静态类型的编程语言,每个变量都必须在声明时确定其数据类型。C++中包含基本数据类型和用户自定义数据类型。以下是基本数据类型和变量声明的示例代码:
// 基本数据类型 int myInt = 5; // 整型 bool myBool = true; // 布尔型 double myDouble = 3.14; // 双精度浮点型 char myChar = 'a'; // 字符型 // 用户自定义数据类型 struct Person { string name; int age; }; Person myPerson = {"John", 25};
在变量声明中,可以用关键字const来指示某个值是常量:
const int myConst = 10;
二、控制结构
条件语句
条件语句根据表达式的值选择性执行不同的代码块。以下是if语句和switch语句的示例代码:
// if语句 if (myInt > 0) { cout << "Positive" << endl; } else if (myInt < 0) { cout << "Negative" << endl; } else { cout << "Zero" << endl; } // switch语句 switch (myChar) { case 'a': cout << "A" << endl; break; case 'b': cout << "B" << endl; break; default: cout << "Other" << endl; }
循环语句
循环语句重复执行某个代码块,C++中包括for循环、while循环和do-while循环。以下是它们的示例代码:
// for循环 for (int i = 0; i < 5; i++) { cout << i << endl; } // while循环 int i = 0; while (i < 5) { cout << i << endl; i++; } // do-while循环 int i = 0; do { cout << i << endl; i++; } while (i < 5);
三、函数定义
函数定义是将某个功能封装在一个单独的代码块中,并在需要时调用它。以下是函数定义的示例代码:
int mySum(int a, int b) { return a + b; } void myPrint(string s) { cout << s << endl; } int main() { int sum = mySum(1, 2); myPrint("Hello world!"); return 0; }
四、类和对象
类是一种用户自定义的数据结构,它可以将数据和操作封装在一起。对象是类的一个实例。以下是类和对象的示例代码:
class Rectangle { public: int width; int height; int getArea() { return width * height; } }; Rectangle myRect; myRect.width = 5; myRect.height = 10; int area = myRect.getArea();
五、指针和引用
指针和引用是C++的重要特性,它们允许我们直接操作内存地址。以下是指针和引用的示例代码:
// 指针 int myInt = 5; int* myPtr = &myInt; *myPtr = 10; // 引用 int myInt = 5; int& myRef = myInt; myRef = 10;
六、STL容器
C++标准模板库(STL)提供了各种数据结构的容器,包括向量、列表和映射等。以下是向量和映射的示例代码:
// 向量 vector myVec = {1, 2, 3}; myVec.push_back(4); // 映射 map myMap = {{"apple", 1}, {"banana", 2}}; myMap["orange"] = 3;
七、文件操作
C++中提供了文件流库来进行文件操作。以下是读取和写入文件的示例代码:
// 读取文件 ifstream myfile("example.txt"); string line; while (getline(myfile, line)) { cout << line << endl; } myfile.close(); // 写入文件 ofstream myfile("example.txt"); myfile << "Hello world!" << endl; myfile.close();
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/159126.html