一、數據類型和變數聲明
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/zh-tw/n/159126.html
微信掃一掃
支付寶掃一掃