一、C++基礎語法
C++是一種多範式的編程語言,支持面向過程、面向對象、泛型等多種編程範式。下面我們從基本語法和常用數據類型入手,來詳細闡述C++的入門內容。
1. C++的基本語法
#include <iostream> using namespace std; int main() { // 這是一個注釋,不會影響程序運行 cout <<"Hello world!"<< endl; return 0; }
2. 常用數據類型
int a = 10; double b = 3.14; char c = 'a'; bool d = true;
3. 流程式控制制語句
int a = 10; if (a > 5) { cout <<"a is greater than 5"<< endl; } else { cout <<"a is less than or equal to 5"<< endl; } for (int i = 0; i < 10; i++) { cout <<i< 0) { cout <<a<<"\t"; a--; }
二、面向對象編程
面向對象是C++的最大特色,C++中支持類、對象、繼承、多態等重要的面向對象概念。下面我們以一個計算器程序為例,來詳細介紹面向對象的用法。
1. 類和對象
class Calculator { public: int add(int a, int b) { return a + b; } int minus(int a, int b) { return a - b; } }; int main() { Calculator calc; int a = 10, b = 5; cout <<"a + b = "<< calc.add(a, b)<< endl; cout <<"a - b = "<< calc.minus(a, b)<< endl; return 0; }
2. 繼承和多態
class Animal { public: virtual void sound() = 0; }; class Dog : public Animal { public: virtual void sound() { cout <<"Wang Wang!"<< endl; } }; class Cat : public Animal { public: virtual void sound() { cout <<"Miao Miao!"<sound(); pAnimal = new Cat(); pAnimal->sound(); return 0; }
三、C++ STL
STL(Standard Template Library)是C++的標準庫,包含了常用的容器、演算法和迭代器等。STL提供了封裝性、泛型性和可移植性,是C++編程中不可或缺的部分。
1. 容器
#include <vector> vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); for (vector<int>::iterator it = v.begin(); it != v.end(); it++) { cout <<*it<<"\t"; }
2. 演算法
#include <algorithm> vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); cout <<"sum: "<< accumulate(v.begin(), v.end(), 0)<< endl; reverse(v.begin(), v.end()); for (vector<int>::iterator it = v.begin(); it != v.end(); it++) { cout <<*it<<"\t"; }
四、高級特性
除了基本語法、面向對象和STL,C++還有一些高級特性值得我們深入學習,如Lambda表達式、多線程編程和常用的異常處理等。
1. Lambda表達式
int main() { int a = 10; auto f = [a](int b) -> int { return a + b; }; cout <<f(20)<< endl; return 0; }
2. 多線程編程
#include <thread> void print(int x) { for (int i = 0; i < 10; i++) { cout <<x<<"\t"; } } int main() { thread t1(print, 1); thread t2(print, 2); t1.join(); t2.join(); return 0; }
3. 異常處理
int main() { try { int a = 10, b = 0; if (b == 0) { throw "divide by zero"; } cout <<a/b<< endl; } catch (const char* msg) { cout <<"Exception caught: "<< msg<< endl; } return 0; }
參考文獻:
– 參考教材:C++ Primer Plus, 6th Edition.
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/256865.html