1.面向對象
1.1 定義
面向對象編程是一種程序設計方法,它將數據和操作數據的方法封裝在一起,形成類。類是一種用戶自定義的數據類型,它包含了數據和對數據的操作方法。面向對象編程的特點包括封裝、繼承、多態
1.2 訪問控制符
· public 公有屬性,方法。都可以訪問
· protected 只能自己和子類訪問
· private 只能自己訪問
#include <iostream>
#include <string>
using namespace std;
class Test
{
public:string name;int age;void show_name(){cout << name << endl;};
};int main()
{Test t;t.name = "Tom";t.age = 10;t.show_name();return 0;
}
1.3 構造函數
構造函數是特殊的成員函數,在對象創建時自動調用,用于初始化對象的狀態
Person(int a){} — 類名(參數列表){函數體}
特點如下:
· 構造函數無返回值,也不需要加void,構造函數沒有函數類型。
· 構造函數的函數名稱要與類名一致
· 構造函數具有形參列表,并可以發生函數重載
· 編譯器會自動調用構造函數,無需手動調用,并且只調用一次
#include <iostream>
#include <string>using namespace std;class Test
{
public:Test(){cout << " first test " << endl;}Test(int a){cout << " test a : " << a << endl;}};// 根據參數的不同,調用不同的構造函數
int main()
{Test t;Test ta(1);return 0;
}
//輸出結果
//first test
//test a : 1
1.4 構造函數初始化列表
· 沒使用初始化列表的構造函數,初始化成員變量會先調用默認構造函數,然后再賦值。
而參數列表初始化則避免了這種情況,直接通過初始化列表進行初始化,從而提高了效率。
· const成員和引用類型的成員(&)必須在初始化列表中初始化,因為它們不能在構造函數體內賦值。
· 如果成員是一個類類型對象,那么使用初始化列表可以直接調用其構造函數進行初始化,而不是先調用默認構造函數再進行賦值。
1.4.1基本示例
class Test
{
public:Test(int a, int b): num1(a), num2(b){cout << " num1的初始化值為a, num2的初始化值為b " << endl;}
private:int num1;int num2;
};
1.4.2 const 成員和引用成員 示例
class Test
{
public:Test(int a, int b): num1(a), num2(b){cout << "構造函數初始化" << endl;}
private:const int num1;int & num2;
};
1.4.3
class A
{
public:A(int a){cout << " a : "