欧美free性护士vide0shd,老熟女,一区二区三区,久久久久夜夜夜精品国产,久久久久久综合网天天,欧美成人护士h版

首頁綜合 正文
目錄

柚子快報激活碼778899分享:C++詳解

柚子快報激活碼778899分享:C++詳解

http://yzkb.51969.com/

C++詳解

文章目錄

C++詳解1 內(nèi)存分區(qū)模型1.1 程序運行前1.2 程序運行后1.3 new操作符

2 引用2.1 引用的基本使用2.2 引用注意事項2.3 引用做函數(shù)參數(shù)2.4 引用做函數(shù)返回值2.5 引用的本質(zhì)2.6 常量引用

3 函數(shù)提高3.1 函數(shù)默認(rèn)參數(shù)3.2 函數(shù)占位參數(shù)3.3 函數(shù)重載3.3.1 函數(shù)重載概述3.3.2 函數(shù)重載注意事項

4 類和對象4.1 封裝4.1.1 封裝的意義4.1.2 struct和class區(qū)別4.1.3 成員屬性設(shè)置為私有

4.2 對象的初始化和清理4.2.1 構(gòu)造函數(shù)和析構(gòu)函數(shù)4.2.2 構(gòu)造函數(shù)的分類及調(diào)用4.2.3 拷貝構(gòu)造函數(shù)調(diào)用時機(jī)4.2.4 構(gòu)造函數(shù)調(diào)用規(guī)則4.2.5 深拷貝與淺拷貝4.2.6 初始化列表4.2.7 類對象作為類成員4.2.8 靜態(tài)成員

4.3 C++對象模型和this指針4.3.1 成員變量和成員函數(shù)分開存儲4.3.2 this指針概念4.3.3 空指針訪問成員函數(shù)4.3.4 const修飾成員函數(shù)4.3.5 GradeBook類

4.4 友元4.4.1 全局函數(shù)做友元4.4.2 類做友元4.4.3 成員函數(shù)做友元4.4.4 Date類作為person類的友元

4.5 運算符重載4.5.1 加號運算符重載4.5.2 左移運算符重載4.5.3 遞增運算符重載4.5.4 賦值運算符重載4.5.5 關(guān)系運算符重載4.5.6 函數(shù)調(diào)用運算符重載4.5.7 重載+, - ,*, /, >>,<<運算符

4.6 繼承4.6.1 繼承的基本語法4.6.2 繼承方式4.6.3 繼承中的對象模型4.6.4 繼承中構(gòu)造和析構(gòu)順序4.6.5 繼承同名成員處理方式4.6.6 繼承同名靜態(tài)成員處理方式4.6.7 多繼承語法4.6.8 菱形繼承

4.7 多態(tài)4.7.1 多態(tài)的基本介紹4.7.2 純虛函數(shù)和抽象類4.7.3 虛析構(gòu)和純虛析構(gòu)4.7.4 多態(tài)案例一-計算器類4.7.5 多態(tài)案例二-制作飲品4.7.6 多態(tài)案例三-電腦組裝4.7.7 繼承與多態(tài)案例

5 文件操作5.1文本文件5.1.1寫文件5.1.2讀文件

5.2 二進(jìn)制文件5.2.1 寫文件5.2.2 讀文件

1 內(nèi)存分區(qū)模型

C++程序在執(zhí)行時,將內(nèi)存大方向劃分為4個區(qū)域

代碼區(qū):存放函數(shù)體的二進(jìn)制代碼,由操作系統(tǒng)進(jìn)行管理的。全局區(qū):存放全局變量和靜態(tài)變量以及常量。棧區(qū):由編譯器自動分配釋放, 存放函數(shù)的參數(shù)值,局部變量等。堆區(qū):由程序員分配和釋放,若程序員不釋放,程序結(jié)束時由操作系統(tǒng)回收。

內(nèi)存四區(qū)意義:

? 不同區(qū)域存放的數(shù)據(jù),賦予不同的生命周期, 給我們更大的靈活編程。

1.1 程序運行前

? 在程序編譯后,生成了exe可執(zhí)行程序,未執(zhí)行該程序前分為兩個區(qū)域。

? 代碼區(qū):

存放 CPU 執(zhí)行的機(jī)器指令。 代碼區(qū)是共享的,共享的目的是對于頻繁被執(zhí)行的程序,只需要在內(nèi)存中有一份代碼即可。 代碼區(qū)是只讀的,使其只讀的原因是防止程序意外地修改了它的指令。

? 全局區(qū):

全局變量和靜態(tài)變量存放在此。 全局區(qū)還包含了常量區(qū), 字符串常量和其他常量也存放在此。 該區(qū)域的數(shù)據(jù)在程序結(jié)束后由操作系統(tǒng)釋放。

? 例1.1.1

#include

#include // 為了使用 uintptr_t

using namespace std;

// 全局變量

int g_a = 10;

int g_b = 10;

// 全局常量

const int c_g_a = 10;

const int c_g_b = 10;

int main()

{

// 局部變量

int a = 10;

int b = 10;

// 打印地址

cout << "局部變量a地址為: " << (void*)&a << endl;

cout << "局部變量b地址為: " << (void*)&b << endl;

cout << "全局變量g_a地址為: " << (void*)&g_a << endl;

cout << "全局變量g_b地址為: " << (void*)&g_b << endl;

// 靜態(tài)變量

static int s_a = 10;

static int s_b = 10;

cout << "靜態(tài)變量s_a地址為: " << (void*)&s_a << endl;

cout << "靜態(tài)變量s_b地址為: " << (void*)&s_b << endl;

cout << "字符串常量\"hello world\"地址為: " << (void*)"hello world" << endl;

cout << "字符串常量\"hello world1\"地址為: " << (void*)"hello world1" << endl;

cout << "全局常量c_g_a地址為: " << (void*)&c_g_a << endl;

cout << "全局常量c_g_b地址為: " << (void*)&c_g_b << endl;

const int c_l_a = 10;

const int c_l_b = 10;

cout << "局部常量c_l_a地址為: " << (void*)&c_l_a << endl;

cout << "局部常量c_l_b地址為: " << (void*)&c_l_b << endl;

return 0;

}

? 結(jié)果如下:

局部變量a地址為: 0x61fe1c

局部變量b地址為: 0x61fe18

全局變量g_a地址為: 0x403010

全局變量g_b地址為: 0x403014

靜態(tài)變量s_a地址為: 0x403018

靜態(tài)變量s_b地址為: 0x40301c

字符串常量"hello world"地址為: 0x4040a9

字符串常量"hello world1"地址為: 0x4040da

全局常量c_g_a地址為: 0x404004

全局常量c_g_b地址為: 0x404008

局部常量c_l_a地址為: 0x61fe14

局部常量c_l_b地址為: 0x61fe10

Process returned 0 (0x0) execution time : 0.011 s

Press any key to continue.

? 總結(jié):

C++中在程序運行前分為全局區(qū)和代碼區(qū)。代碼區(qū)特點是共享和只讀。全局區(qū)中存放全局變量、靜態(tài)變量、常量。常量區(qū)中存放 const修飾的全局常量 和 字符串常量。

1.2 程序運行后

? 棧區(qū):

由編譯器自動分配釋放, 存放函數(shù)的參數(shù)值,局部變量等。 注意事項:不要返回局部變量的地址,棧區(qū)開辟的數(shù)據(jù)由編譯器自動釋放。

? 例1.2.1

#include

using namespace std;

int * func()

{

int a = 10;

return &a;

}

int main()

{

int *p = func();

cout << *p << endl;

cout << *p << endl;

return 0;

}

? 結(jié)果如下:

10

10

Process returned 0 (0x0) execution time : 0.010 s

Press any key to continue.

? 堆區(qū):

由程序員分配釋放,若程序員不釋放,程序結(jié)束時由操作系統(tǒng)回收。 在C++中主要利用new在堆區(qū)開辟內(nèi)存。

? 例1.2.2

#include

using namespace std;

int* func()

{

int* a = new int(10);

return a;

}

int main()

{

int *p = func();

cout << *p << endl;

cout << *p << endl;

return 0;

}

? 結(jié)果如下:

10

10

Process returned 0 (0x0) execution time : 0.043 s

Press any key to continue.

? 總結(jié):

堆區(qū)數(shù)據(jù)由程序員管理開辟和釋放。 堆區(qū)數(shù)據(jù)利用new關(guān)鍵字進(jìn)行開辟內(nèi)存。

1.3 new操作符

? C++中利用new操作符在堆區(qū)開辟數(shù)據(jù)。

? 堆區(qū)開辟的數(shù)據(jù),由程序員手動開辟,手動釋放,釋放利用操作符 delete

? 語法: new 數(shù)據(jù)類型

? 利用new創(chuàng)建的數(shù)據(jù),會返回該數(shù)據(jù)對應(yīng)的類型的指針。

? 例1.3.1

#include

using namespace std;

int* func()

{

int* a = new int(10);

return a;

}

int main()

{

int *p = func();

cout << *p << endl;

cout << *p << endl;

//利用delete釋放堆區(qū)數(shù)據(jù)

delete p;

//cout << *p << endl; //報錯,釋放的空間不可訪問

return 0;

}

? 結(jié)果如下:

10

10

Process returned 0 (0x0) execution time : 0.010 s

Press any key to continue.

? 例1.3.2

#include

using namespace std;

//堆區(qū)開辟數(shù)組

int main()

{

int* arr = new int[10];

for (int i = 0; i < 10; i++)

{

arr[i] = i + 100;

}

for (int i = 0; i < 10; i++)

{

cout << arr[i] << endl;

}

//釋放數(shù)組 delete 后加 []

delete[] arr;

return 0;

}

? 結(jié)果如下:

100

101

102

103

104

105

106

107

108

109

Process returned 0 (0x0) execution time : 0.011 s

Press any key to continue.

2 引用

2.1 引用的基本使用

? 作用: 給變量起別名

? 語法:數(shù)據(jù)類型 &別名 = 原名

? 例2.1.1

#include

using namespace std;

int main()

{

int a = 10;

int &b = a;

cout << "a = " << a << endl;

cout << "b = " << b << endl;

b = 100;

cout << "a = " << a << endl;

cout << "b = " << b << endl;

return 0;

}

? 結(jié)果如下:

a = 10

b = 10

a = 100

b = 100

Process returned 0 (0x0) execution time : 0.011 s

Press any key to continue.

2.2 引用注意事項

引用必須初始化。引用在初始化后,不可以改變。

? 例2.2.1

#include

using namespace std;

int main()

{

int a = 10;

int b = 20;

//int &c; //錯誤,引用必須初始化

int &c = a; //一旦初始化后,就不可以更改

c = b; //這是賦值操作,不是更改引用

cout << "a = " << a << endl;

cout << "b = " << b << endl;

cout << "c = " << c << endl;

return 0;

}

? 結(jié)果如下:

a = 20

b = 20

c = 20

Process returned 0 (0x0) execution time : 0.026 s

Press any key to continue.

2.3 引用做函數(shù)參數(shù)

? 作用: 函數(shù)傳參時,可以利用引用的技術(shù)讓形參修飾實參。

? 優(yōu)點: 可以簡化指針修改實參。

? 例2.3.1

#include

using namespace std;

//1. 值傳遞

void mySwap01(int a, int b)

{

int temp = a;

a = b;

b = temp;

}

//2. 地址傳遞

void mySwap02(int* a, int* b)

{

int temp = *a;

*a = *b;

*b = temp;

}

//3. 引用傳遞

void mySwap03(int& a, int& b)

{

int temp = a;

a = b;

b = temp;

}

int main()

{

int a = 10;

int b = 20;

mySwap01(a, b);

cout << "a:" << a << " b:" << b << endl;

mySwap02(&a, &b);

cout << "a:" << a << " b:" << b << endl;

mySwap03(a, b);

cout << "a:" << a << " b:" << b << endl;

return 0;

}

? 結(jié)果如下:

a:10 b:20

a:20 b:10

a:10 b:20

Process returned 0 (0x0) execution time : 0.039 s

Press any key to continue.

? 總結(jié):

通過引用參數(shù)產(chǎn)生的效果同按地址傳遞是一樣的。引用的語法更清楚簡單。

2.4 引用做函數(shù)返回值

? 作用:引用是可以作為函數(shù)的返回值存在的。

? 注意:不要返回局部變量引用。

? 用法:函數(shù)調(diào)用作為左值。

? 例2.4.1

#include

using namespace std;

//返回局部變量引用

int& test01()

{

int a = 10; //局部變量

return a;

}

//返回靜態(tài)變量引用

int& test02()

{

static int a = 20; // 靜態(tài)變量,存放在全局區(qū),全局區(qū)上的數(shù)據(jù)在程序結(jié)束后系統(tǒng)釋放

return a;

}

int main()

{

//不能返回局部變量的引用

//int& ref1 = test01();

//cout << "ref1 = " << ref1 << endl; // 程序崩潰

//如果函數(shù)做左值,那么必須返回引用

int& ref2 = test02();

cout << "ref2 = " << ref2 << endl;

cout << "ref2 = " << ref2 << endl;

test02() = 1000; // 如果函數(shù)的返回值是引用,這個函數(shù)調(diào)用可以作為左值。

cout << "ref2 = " << ref2 << endl;

cout << "ref2 = " << ref2 << endl;

return 0;

}

? 結(jié)果如下:

ref2 = 20

ref2 = 20

ref2 = 1000

ref2 = 1000

Process returned 0 (0x0) execution time : 0.038 s

Press any key to continue.

2.5 引用的本質(zhì)

? 本質(zhì):引用的本質(zhì)在c++內(nèi)部實現(xiàn)是一個指針常量。

? 例2.5.1

#include

using namespace std;

//發(fā)現(xiàn)是引用,轉(zhuǎn)換為 int* const ref = &a;

void func(int& ref)

{

ref = 100; // ref是引用,轉(zhuǎn)換為*ref = 100

}

int main()

{

int a = 10;

//自動轉(zhuǎn)換為 int* const ref = &a; 指針常量是指針指向不可改,也說明為什么引用不可更改

int& ref = a;

ref = 20; //內(nèi)部發(fā)現(xiàn)ref是引用,自動幫我們轉(zhuǎn)換為: *ref = 20;

cout << "a:" << a << endl;

cout << "ref:" << ref << endl;

func(a);

return 0;

}

? 結(jié)果如下:

a:20

ref:20

Process returned 0 (0x0) execution time : 0.034 s

Press any key to continue.

? 結(jié)論:

C++推薦用引用技術(shù),因為語法方便,引用本質(zhì)是指針常量,但是所有的指針操作編譯器都幫我們做了。

2.6 常量引用

? 作用: 常量引用主要用來修飾形參,防止誤操作。

? 在函數(shù)形參列表中,可以加const修飾形參,防止形參改變實參。

? 例2.6.1

#include

using namespace std;

//引用使用的場景,通常用來修飾形參

void showValue(const int& v)

{

//v += 10;

cout << v << endl;

}

int main()

{

//int& ref = 10; 引用本身需要一個合法的內(nèi)存空間,因此這行錯誤

//加入const就可以了,編譯器優(yōu)化代碼,int temp = 10; const int& ref = temp;

const int& ref = 10;

//ref = 100; //加入const后不可以修改變量

cout << ref << endl;

//函數(shù)中利用常量引用防止誤操作修改實參

int a = 10;

showValue(a);

return 0;

}

? 結(jié)果如下:

10

10

Process returned 0 (0x0) execution time : 0.010 s

Press any key to continue.

3 函數(shù)提高

3.1 函數(shù)默認(rèn)參數(shù)

? 在C++中,函數(shù)的形參列表中的形參是可以有默認(rèn)值的。

? 語法: 返回值類型 函數(shù)名 (參數(shù)= 默認(rèn)值){}

? 例3.1.1

#include

using namespace std;

int func(int a, int b = 10, int c = 10)

{

return a + b + c;

}

//1. 如果某個位置參數(shù)有默認(rèn)值,那么從這個位置往后,從左向右,必須都要有默認(rèn)值

//2. 如果函數(shù)聲明有默認(rèn)值,函數(shù)實現(xiàn)的時候就不能有默認(rèn)參數(shù)

int func2(int a = 10, int b = 10);

int func2(int a, int b)

{

return a + b;

}

int main()

{

cout << "ret = " << func(20, 20) << endl;

cout << "ret = " << func(100) << endl;

return 0;

}

? 結(jié)果如下:

ret = 50

ret = 120

Process returned 0 (0x0) execution time : 0.011 s

Press any key to continue.

3.2 函數(shù)占位參數(shù)

? C++中函數(shù)的形參列表里可以有占位參數(shù),用來做占位,調(diào)用函數(shù)時必須填補(bǔ)該位置。

? 語法: 返回值類型 函數(shù)名 (數(shù)據(jù)類型){}

? 例3.2.2

#include

using namespace std;

//函數(shù)占位參數(shù) ,占位參數(shù)也可以有默認(rèn)參數(shù)

void func(int a, int)

{

cout << "this is func" << endl;

}

int main()

{

func(10,10); //占位參數(shù)必須填補(bǔ)

return 0;

}

? 結(jié)果如下:

this is func

Process returned 0 (0x0) execution time : 0.009 s

Press any key to continue.

3.3 函數(shù)重載

3.3.1 函數(shù)重載概述

? 作用: 函數(shù)名可以相同,提高復(fù)用性。

? 函數(shù)重載滿足條件:

同一個作用域下。函數(shù)名稱相同。函數(shù)參數(shù)類型不同 或者 個數(shù)不同 或者 順序不同。

? 注意: 函數(shù)的返回值不可以作為函數(shù)重載的條件。

? 例3.3.1

#include

using namespace std;

//函數(shù)重載需要函數(shù)都在同一個作用域下

void func()

{

cout << "func 的調(diào)用!" << endl;

}

void func(int a)

{

cout << "func (int a) 的調(diào)用!" << endl;

}

void func(double a)

{

cout << "func (double a)的調(diào)用!" << endl;

}

void func(int a ,double b)

{

cout << "func (int a ,double b) 的調(diào)用!" << endl;

}

void func(double a ,int b)

{

cout << "func (double a ,int b)的調(diào)用!" << endl;

}

//函數(shù)返回值不可以作為函數(shù)重載條件

//int func(double a, int b)

//{

// cout << "func (double a ,int b)的調(diào)用!" << endl;

//}

int main()

{

func();

func(10);

func(3.14);

func(10,3.14);

func(3.14 , 10);

return 0;

}

? 結(jié)果如下:

func 的調(diào)用!

func (int a) 的調(diào)用!

func (double a)的調(diào)用!

func (int a ,double b) 的調(diào)用!

func (double a ,int b)的調(diào)用!

Process returned 0 (0x0) execution time : 0.037 s

Press any key to continue.

3.3.2 函數(shù)重載注意事項

引用作為重載條件。函數(shù)重載碰到函數(shù)默認(rèn)參數(shù)。

? 例3.3.2

#include

using namespace std;

//函數(shù)重載注意事項

//1、引用作為重載條件

void func(int &a)

{

cout << "func (int &a) 調(diào)用 " << endl;

}

void func(const int &a)

{

cout << "func (const int &a) 調(diào)用 " << endl;

}

//2、函數(shù)重載碰到函數(shù)默認(rèn)參數(shù)

void func2(int a, int b = 10)

{

cout << "func2(int a, int b = 10) 調(diào)用" << endl;

}

void func2(int a)

{

cout << "func2(int a) 調(diào)用" << endl;

}

int main()

{

int a = 10;

func(a); //調(diào)用無const

func(10);//調(diào)用有const

//func2(10); //碰到默認(rèn)參數(shù)產(chǎn)生歧義,需要避免

return 0;

}

? 結(jié)果如下:

func (int &a) 調(diào)用

func (const int &a) 調(diào)用

Process returned 0 (0x0) execution time : 0.006 s

Press any key to continue.

4 類和對象

? C++面向?qū)ο蟮娜筇匦詾椋悍庋b、繼承、多態(tài)

? C++認(rèn)為萬事萬物都皆為對象,對象上有其屬性和行為

? 例如:

人可以作為對象,屬性有姓名、年齡、身高、體重…,行為有走、跑、跳、吃飯、唱歌… 車也可以作為對象,屬性有輪胎、方向盤、車燈…,行為有載人、放音樂、放空調(diào)… 具有相同性質(zhì)的對象,我們可以抽象稱為類,人屬于人類,車屬于車類

4.1 封裝

4.1.1 封裝的意義

? 封裝是C++面向?qū)ο笕筇匦灾?/p>

? 語法: class 類名{ 訪問權(quán)限: 屬性 / 行為 };

? 封裝的意義:

在設(shè)計類的時候,屬性和行為寫在一起,表現(xiàn)事物。 類在設(shè)計時,可以把屬性和行為放在不同的權(quán)限下,加以控制

訪問權(quán)限有三種:

public 公共權(quán)限protected 保護(hù)權(quán)限private 私有權(quán)限

? 例4.1.1.1 設(shè)計一個圓類,求圓的周長。

#include

using namespace std;

//圓周率

const double PI = 3.14;

//1、封裝的意義

//將屬性和行為作為一個整體,用來表現(xiàn)生活中的事物

//封裝一個圓類,求圓的周長

//class代表設(shè)計一個類,后面跟著的是類名

class Circle

{

public: //訪問權(quán)限 公共的權(quán)限

//屬性

int m_r;//半徑

//行為

//獲取到圓的周長

double calculateZC()

{

//2 * pi * r

//獲取圓的周長

return 2 * PI * m_r;

}

};

int main()

{

//通過圓類,創(chuàng)建圓的對象

// c1就是一個具體的圓

Circle c1;

c1.m_r = 10; //給圓對象的半徑 進(jìn)行賦值操作

//2 * pi * 10 = = 62.8

cout << "圓的周長為: " << c1.calculateZC() << endl;

return 0;

}

? 結(jié)果如下:

圓的周長為: 62.8

Process returned 0 (0x0) execution time : 0.008 s

Press any key to continue.

? 例4.1.1.2 設(shè)計一個學(xué)生類,屬性有姓名和學(xué)號,可以給姓名和學(xué)號賦值,可以顯示學(xué)生的姓名和學(xué)號。

#include

using namespace std;

//學(xué)生類

class Student

{

public:

void setName(string name)

{

m_name = name;

}

void setID(int id)

{

m_id = id;

}

void showStudent()

{

cout << "name:" << m_name << '\n' << "ID:" << m_id << endl;

}

public:

string m_name;

int m_id;

};

int main()

{

Student stu;

stu.setName("小杜");

stu.setID(10086);

stu.showStudent();

return 0;

}

? 結(jié)果如下:

name:小杜

ID:10086

Process returned 0 (0x0) execution time : 0.009 s

Press any key to continue.

? 例4.1.1.3

#include

using namespace std;

// 三種權(quán)限

// 公共權(quán)限 public 類內(nèi)可以訪問 類外可以訪問

// 保護(hù)權(quán)限 protected 類內(nèi)可以訪問 類外不可以訪問

// 私有權(quán)限 private 類內(nèi)可以訪問 類外不可以訪問

class Person

{

public:

string m_Name; // 姓名 公共權(quán)限

void func()

{

m_Name = "張三";

m_Car = "拖拉機(jī)";

m_Password = 123456;

}

protected:

string m_Car; // 汽車 保護(hù)權(quán)限

private:

int m_Password; // 銀行卡密碼 私有權(quán)限

};

int main()

{

Person p;

p.m_Name = "李四";

//p.m_Car = "奔馳"; //保護(hù)權(quán)限類外訪問不到

//p.m_Password = 123; //私有權(quán)限類外訪問不到

return 0;

}

? 結(jié)果如下:

Process returned 0 (0x0) execution time : 0.010 s

Press any key to continue.

4.1.2 struct和class區(qū)別

? 在C++中 struct和class唯一的區(qū)別就在于 默認(rèn)的訪問權(quán)限不同。

? 區(qū)別:

struct 默認(rèn)權(quán)限為公共。class 默認(rèn)權(quán)限為私有。

? 例4.1.2

#include

using namespace std;

class C1

{

int m_A; //默認(rèn)是私有權(quán)限

};

struct C2

{

int m_A; //默認(rèn)是公共權(quán)限

};

int main()

{

//C1 c1;

//c1.m_A = 10; //錯誤,訪問權(quán)限是私有

C2 c2;

c2.m_A = 10; //正確,訪問權(quán)限是公共

return 0;

}

? 結(jié)果如下:

Process returned 0 (0x0) execution time : 0.010 s

Press any key to continue.

4.1.3 成員屬性設(shè)置為私有

? 優(yōu)點:

將所有成員屬性設(shè)置為私有,可以自己控制讀寫權(quán)限。對于寫權(quán)限,我們可以檢測數(shù)據(jù)的有效性。

? 例4.1.3

#include

using namespace std;

class Person

{

public:

//姓名設(shè)置可讀可寫

void setName(string name)

{

m_Name = name;

}

string getName()

{

return m_Name;

}

//獲取年齡

int getAge()

{

return m_Age;

}

//設(shè)置年齡

void setAge(int age)

{

if (age < 0 || age > 150)

{

cout << "你個老妖精!" << endl;

return;

}

m_Age = age;

}

//情人設(shè)置為只寫

void setLover(string lover)

{

m_Lover = lover;

}

private:

string m_Name; //可讀可寫 姓名

int m_Age; //只讀 年齡

string m_Lover; //只寫 情人

};

int main()

{

Person p;

//姓名設(shè)置

p.setName("張三");

cout << "姓名: " << p.getName() << endl;

//年齡設(shè)置

p.setAge(50);

cout << "年齡: " << p.getAge() << endl;

//情人設(shè)置

p.setLover("蒼井");

//cout << "情人: " << p.m_Lover << endl; //只寫屬性,不可以讀取

return 0;

}

? 結(jié)果如下:

姓名: 張三

年齡: 50

Process returned 0 (0x0) execution time : 0.011 s

Press any key to continue.

4.2 對象的初始化和清理

生活中我們買的電子產(chǎn)品都基本會有出廠設(shè)置,在某一天我們不用時候也會刪除一些自己信息數(shù)據(jù)保證安全。C++中的面向?qū)ο髞碓从谏?,每個對象也都會有初始設(shè)置以及 對象銷毀前的清理數(shù)據(jù)的設(shè)置。

4.2.1 構(gòu)造函數(shù)和析構(gòu)函數(shù)

? 對象的初始化和清理也是兩個非常重要的安全問題

一個對象或者變量沒有初始狀態(tài),對其使用后果是未知。 同樣的使用完一個對象或變量,沒有及時清理,也會造成一定的安全問題。

? c++利用了構(gòu)造函數(shù)和析構(gòu)函數(shù)解決上述問題,這兩個函數(shù)將會被編譯器自動調(diào)用,完成對象初始化和清理工作。

? 對象的初始化和清理工作是編譯器強(qiáng)制要我們做的事情,因此如果我們不提供構(gòu)造和析構(gòu),編譯器會提供。

? 編譯器提供的構(gòu)造函數(shù)和析構(gòu)函數(shù)是空實現(xiàn)。

構(gòu)造函數(shù):主要作用在于創(chuàng)建對象時為對象的成員屬性賦值,構(gòu)造函數(shù)由編譯器自動調(diào)用,無須手動調(diào)用。析構(gòu)函數(shù):主要作用在于對象銷毀前系統(tǒng)自動調(diào)用,執(zhí)行一些清理工作。

? 構(gòu)造函數(shù)語法:類名(){}

構(gòu)造函數(shù),沒有返回值也不寫void函數(shù)名稱與類名相同構(gòu)造函數(shù)可以有參數(shù),因此可以發(fā)生重載程序在調(diào)用對象時候會自動調(diào)用構(gòu)造,無須手動調(diào)用,而且只會調(diào)用一次

? 析構(gòu)函數(shù)語法: ~類名(){}

析構(gòu)函數(shù),沒有返回值也不寫void函數(shù)名稱與類名相同,在名稱前加上符號 ~析構(gòu)函數(shù)不可以有參數(shù),因此不可以發(fā)生重載程序在對象銷毀前會自動調(diào)用析構(gòu),無須手動調(diào)用,而且只會調(diào)用一次

? 例4.2.1

#include

using namespace std;

class Person

{

public:

//構(gòu)造函數(shù)

Person()

{

cout << "Person的構(gòu)造函數(shù)調(diào)用" << endl;

}

//析構(gòu)函數(shù)

~Person()

{

cout << "Person的析構(gòu)函數(shù)調(diào)用" << endl;

}

};

void test01()

{

Person p;

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

Person的構(gòu)造函數(shù)調(diào)用

Person的析構(gòu)函數(shù)調(diào)用

Process returned 0 (0x0) execution time : 0.012 s

Press any key to continue.

4.2.2 構(gòu)造函數(shù)的分類及調(diào)用

? 兩種分類方式:

按參數(shù)分為: 有參構(gòu)造和無參構(gòu)造 按類型分為: 普通構(gòu)造和拷貝構(gòu)造

? 三種調(diào)用方式:

括號法 顯示法 隱式轉(zhuǎn)換法

? 例4.2.2

#include

using namespace std;

//1、構(gòu)造函數(shù)分類

// 按照參數(shù)分類分為 有參和無參構(gòu)造 無參又稱為默認(rèn)構(gòu)造函數(shù)

// 按照類型分類分為 普通構(gòu)造和拷貝構(gòu)造

class Person

{

public:

//無參(默認(rèn))構(gòu)造函數(shù)

Person()

{

cout << "無參構(gòu)造函數(shù)!" << endl;

}

//有參構(gòu)造函數(shù)

Person(int a)

{

age = a;

cout << "有參構(gòu)造函數(shù)!" << endl;

}

//拷貝構(gòu)造函數(shù)

Person(const Person& p)

{

age = p.age;

cout << "拷貝構(gòu)造函數(shù)!" << endl;

}

//析構(gòu)函數(shù)

~Person()

{

cout << "析構(gòu)函數(shù)!" << endl;

}

public:

int age;

};

//2、構(gòu)造函數(shù)的調(diào)用

//調(diào)用無參構(gòu)造函數(shù)

void test01()

{

Person p; //調(diào)用無參構(gòu)造函數(shù)

}

//調(diào)用有參的構(gòu)造函數(shù)

void test02()

{

//2.1 括號法,常用

Person p1(10);

//注意1:調(diào)用無參構(gòu)造函數(shù)不能加括號,如果加了編譯器認(rèn)為這是一個函數(shù)聲明

//Person p2();

//2.2 顯式法

Person p2 = Person(10);

Person p3 = Person(p2);

//Person(10)單獨寫就是匿名對象 當(dāng)前行結(jié)束之后,馬上析構(gòu)

//2.3 隱式轉(zhuǎn)換法

Person p4 = 10; // Person p4 = Person(10);

Person p5 = p4; // Person p5 = Person(p4);

//注意2:不能利用 拷貝構(gòu)造函數(shù) 初始化匿名對象 編譯器認(rèn)為是對象聲明

//Person p5(p4);

}

int main()

{

test01();

//test02();

return 0;

}

? 結(jié)果如下:

無參構(gòu)造函數(shù)!

析構(gòu)函數(shù)!

Process returned 0 (0x0) execution time : 0.015 s

Press any key to continue.

4.2.3 拷貝構(gòu)造函數(shù)調(diào)用時機(jī)

? C++中拷貝構(gòu)造函數(shù)調(diào)用時機(jī)通常有三種情況

使用一個已經(jīng)創(chuàng)建完畢的對象來初始化一個新對象。值傳遞的方式給函數(shù)參數(shù)傳值。以值方式返回局部對象。

? 例4.2.3

#include

using namespace std;

class Person

{

public:

Person()

{

cout << "無參構(gòu)造函數(shù)!" << endl;

mAge = 0;

}

Person(int age)

{

cout << "有參構(gòu)造函數(shù)!" << endl;

mAge = age;

}

Person(const Person& p)

{

cout << "拷貝構(gòu)造函數(shù)!" << endl;

mAge = p.mAge;

}

//析構(gòu)函數(shù)在釋放內(nèi)存之前調(diào)用

~Person()

{

cout << "析構(gòu)函數(shù)!" << endl;

}

public:

int mAge;

};

//1. 使用一個已經(jīng)創(chuàng)建完畢的對象來初始化一個新對象

void test01()

{

Person man(100); //p對象已經(jīng)創(chuàng)建完畢

Person newman(man); //調(diào)用拷貝構(gòu)造函數(shù)

Person newman2 = man; //拷貝構(gòu)造

//Person newman3;

//newman3 = man; //不是調(diào)用拷貝構(gòu)造函數(shù),賦值操作

}

//2. 值傳遞的方式給函數(shù)參數(shù)傳值

//相當(dāng)于Person p1 = p;

void doWork(Person p1) {}

void test02()

{

Person p; //無參構(gòu)造函數(shù)

doWork(p);

}

//3. 以值方式返回局部對象

Person doWork2()

{

Person p1;

cout << (int *)&p1 << endl;

return p1;

}

void test03()

{

Person p = doWork2();

cout << (int *)&p << endl;

}

int main()

{

//test01();

//test02();

test03();

return 0;

}

? 結(jié)果如下:

無參構(gòu)造函數(shù)!

0x61fddc

0x61fddc

析構(gòu)函數(shù)!

Process returned 0 (0x0) execution time : 0.014 s

Press any key to continue.

4.2.4 構(gòu)造函數(shù)調(diào)用規(guī)則

? 默認(rèn)情況下,c++編譯器至少給一個類添加3個函數(shù)

1.默認(rèn)構(gòu)造函數(shù)(無參,函數(shù)體為空)

2.默認(rèn)析構(gòu)函數(shù)(無參,函數(shù)體為空)

3.默認(rèn)拷貝構(gòu)造函數(shù),對屬性進(jìn)行值拷貝

? 構(gòu)造函數(shù)調(diào)用規(guī)則如下:

如果用戶定義有參構(gòu)造函數(shù),c++不在提供默認(rèn)無參構(gòu)造,但是會提供默認(rèn)拷貝構(gòu)造。 如果用戶定義拷貝構(gòu)造函數(shù),c++不會再提供其他構(gòu)造函數(shù)。

? 例4.2.4

#include

using namespace std;

class Person

{

public:

//無參(默認(rèn))構(gòu)造函數(shù)

Person()

{

cout << "無參構(gòu)造函數(shù)!" << endl;

}

//有參構(gòu)造函數(shù)

Person(int a)

{

age = a;

cout << "有參構(gòu)造函數(shù)!" << endl;

}

//拷貝構(gòu)造函數(shù)

Person(const Person& p)

{

age = p.age;

cout << "拷貝構(gòu)造函數(shù)!" << endl;

}

//析構(gòu)函數(shù)

~Person()

{

cout << "析構(gòu)函數(shù)!" << endl;

}

public:

int age;

};

void test01()

{

Person p1(18);

//如果不寫拷貝構(gòu)造,編譯器會自動添加拷貝構(gòu)造,并且做淺拷貝操作

Person p2(p1);

cout << "p2的年齡為:" << p2.age << endl;

}

void test02()

{

//如果用戶提供有參構(gòu)造,編譯器不會提供默認(rèn)構(gòu)造,會提供拷貝構(gòu)造

Person p1; //此時如果用戶自己沒有提供默認(rèn)構(gòu)造,會出錯

Person p2(10); //用戶提供的有參

Person p3(p2); //此時如果用戶沒有提供拷貝構(gòu)造,編譯器會提供

//如果用戶提供拷貝構(gòu)造,編譯器不會提供其他構(gòu)造函數(shù)

Person p4; //此時如果用戶自己沒有提供默認(rèn)構(gòu)造,會出錯

Person p5(10); //此時如果用戶自己沒有提供有參,會出錯

Person p6(p5); //用戶自己提供拷貝構(gòu)造

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

有參構(gòu)造函數(shù)!

拷貝構(gòu)造函數(shù)!

p2的年齡為:18

析構(gòu)函數(shù)!

析構(gòu)函數(shù)!

Process returned 0 (0x0) execution time : 0.038 s

Press any key to continue.

4.2.5 深拷貝與淺拷貝

淺拷貝:簡單的賦值拷貝操作。 深拷貝:在堆區(qū)重新申請空間,進(jìn)行拷貝操作。

? 例4.2.5

#include

using namespace std;

class Person

{

public:

//無參(默認(rèn))構(gòu)造函數(shù)

Person()

{

cout << "無參構(gòu)造函數(shù)!" << endl;

}

//有參構(gòu)造函數(shù)

Person(int age ,int height)

{

cout << "有參構(gòu)造函數(shù)!" << endl;

m_age = age;

m_height = new int(height);

}

//拷貝構(gòu)造函數(shù)

Person(const Person& p)

{

cout << "拷貝構(gòu)造函數(shù)!" << endl;

//如果不利用深拷貝在堆區(qū)創(chuàng)建新內(nèi)存,會導(dǎo)致淺拷貝帶來的重復(fù)釋放堆區(qū)問題

m_age = p.m_age;

m_height = new int(*p.m_height);

}

//析構(gòu)函數(shù)

~Person()

{

cout << "析構(gòu)函數(shù)!" << endl;

if (m_height != NULL)

{

delete m_height;

}

}

public:

int m_age;

int* m_height;

};

void test01()

{

Person p1(18, 180);

Person p2(p1);

cout << "p1的年齡:" << p1.m_age << " 身高:" << *p1.m_height << endl;

cout << "p2的年齡:" << p2.m_age << " 身高:" << *p2.m_height << endl;

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

有參構(gòu)造函數(shù)!

拷貝構(gòu)造函數(shù)!

p1的年齡:18 身高:180

p2的年齡:18 身高:180

析構(gòu)函數(shù)!

析構(gòu)函數(shù)!

Process returned 0 (0x0) execution time : 0.031 s

Press any key to continue.

4.2.6 初始化列表

? 作用:

C++提供了初始化列表語法,用來初始化屬性。

? 語法:構(gòu)造函數(shù)():屬性1(值1),屬性2(值2)... {}

? 例4.2.6

#include

using namespace std;

class Person

{

public:

傳統(tǒng)方式初始化

//Person(int a, int b, int c)

//{

// m_A = a;

// m_B = b;

// m_C = c;

//}

//初始化列表方式初始化

Person(int a, int b, int c) :m_A(a), m_B(b), m_C(c) {}

void PrintPerson()

{

cout << "mA:" << m_A << endl;

cout << "mB:" << m_B << endl;

cout << "mC:" << m_C << endl;

}

private:

int m_A;

int m_B;

int m_C;

};

int main()

{

Person p(1, 2, 3);

p.PrintPerson();

return 0;

}

? 結(jié)果如下:

mA:1

mB:2

mC:3

Process returned 0 (0x0) execution time : 0.036 s

Press any key to continue.

4.2.7 類對象作為類成員

? C++類中的成員可以是另一個類的對象,我們稱該成員為 對象成員。

? 例4.2.7.1

class A {}

class B

{

A a;

}

? B類中有對象A作為成員,A為對象成員。

? 那么當(dāng)創(chuàng)建B對象時,A與B的構(gòu)造和析構(gòu)的順序是誰先誰后?

? 例4.2.7.2

#include

using namespace std;

class Phone

{

public:

Phone(string name)

{

m_PhoneName = name;

cout << "Phone構(gòu)造" << endl;

}

~Phone()

{

cout << "Phone析構(gòu)" << endl;

}

string m_PhoneName;

};

class Person

{

public:

//初始化列表可以告訴編譯器調(diào)用哪一個構(gòu)造函數(shù)

Person(string name, string pName) :m_Name(name), m_Phone(pName)

{

cout << "Person構(gòu)造" << endl;

}

~Person()

{

cout << "Person析構(gòu)" << endl;

}

void playGame()

{

cout << m_Name << " 使用" << m_Phone.m_PhoneName << " 牌手機(jī)! " << endl;

}

string m_Name;

Phone m_Phone;

};

void test01()

{

//當(dāng)類中成員是其他類對象時,我們稱該成員為 對象成員

//構(gòu)造的順序是 :先調(diào)用對象成員的構(gòu)造,再調(diào)用本類構(gòu)造

//析構(gòu)順序與構(gòu)造相反

Person p("張三" , "蘋果X");

p.playGame();

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

Phone構(gòu)造

Person構(gòu)造

張三 使用蘋果X 牌手機(jī)!

Person析構(gòu)

Phone析構(gòu)

Process returned 0 (0x0) execution time : 0.009 s

Press any key to continue.

4.2.8 靜態(tài)成員

? 靜態(tài)成員就是在成員變量和成員函數(shù)前加上關(guān)鍵字static,稱為靜態(tài)成員。

? 靜態(tài)成員分為:

靜態(tài)成員變量

所有對象共享同一份數(shù)據(jù)在編譯階段分配內(nèi)存類內(nèi)聲明,類外初始化 靜態(tài)成員函數(shù)

所有對象共享同一個函數(shù)靜態(tài)成員函數(shù)只能訪問靜態(tài)成員變量

? 例4.2.8.1

#include

using namespace std;

class Person

{

public:

static int m_A; //靜態(tài)成員變量

//靜態(tài)成員變量特點:

//1 在編譯階段分配內(nèi)存

//2 類內(nèi)聲明,類外初始化

//3 所有對象共享同一份數(shù)據(jù)

private:

static int m_B; //靜態(tài)成員變量也是有訪問權(quán)限的

};

int Person::m_A = 10;

int Person::m_B = 10;

void test01()

{

//靜態(tài)成員變量兩種訪問方式

//1、通過對象

Person p1;

p1.m_A = 100;

cout << "p1.m_A = " << p1.m_A << endl;

Person p2;

p2.m_A = 200;

cout << "p1.m_A = " << p1.m_A << endl; //共享同一份數(shù)據(jù)

cout << "p2.m_A = " << p2.m_A << endl;

//2、通過類名

cout << "m_A = " << Person::m_A << endl;

//cout << "m_B = " << Person::m_B << endl; //私有權(quán)限訪問不到

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

p1.m_A = 100

p1.m_A = 200

p2.m_A = 200

m_A = 200

Process returned 0 (0x0) execution time : 0.009 s

Press any key to continue.

4.2.9 GradeBook 類

? 題目如下:

? 上機(jī)實驗一,參考上課范例,完成 GradeBook 類(class)設(shè)計。將類定義(class definition)寫在 GradeBook.h 中。 將成員函數(shù)(member function)寫在 GradeBook.cpp 中。編程一個主程序(main)創(chuàng)建兩個 GradeBook 對象,測試類的所有成員函數(shù)。

? GradeBook

-courseName: string //at most 25 characters

-studentCount : int //number of student

-grade: double[] //double array to hold student grades

+setCourseName(name:string)

+setStudentCount(id : int)

+getCourseName():string

+getStudentCount():int

+print() //to display information of GradeBook object

? 程序接口示范

? 上機(jī)實驗一 ? 編程設(shè)計者 王小明 221040700101 ? 請輸入課程名稱:Object Oriented Programming ? 請輸入學(xué)生人數(shù): 120 ? 利用 getCourseName 以及 getStudentCount 顯示第一個對象的信息: ? 課程名稱:Object Oriented Programming ? 學(xué)生人數(shù): 120 ? 請輸入課程名稱:Linear Algebra ? 請輸入學(xué)生人數(shù): 125 ? 利用 print 顯示第二個對象的信息: ? 課程名稱:Linear Algebra ? 學(xué)生人數(shù): 125

? 解答如下:

? main.cpp

#include

#include "Person.h"

using namespace std;

int main()

{

Person myPerson;

// Person myPerson("S.M.Wang", 070145, "蓮花路200號");

cout << "請輸入姓名:" ;

string name;

cin >> name;

cout << "請輸入ID:" ;

int id;

cin >> id;

cout << "請輸入住址:" ;

string address;

cin >> address;

myPerson.setName(name);

myPerson.setID(id);

myPerson.setAddress(address);

myPerson.print();

return 0;

}

? Person.h

#include

using namespace std;

class Person

{

public:

Person();

Person(string name, int id, string address);

~Person();

void setPerson(string name, int id, string address);

void setName(string name);

void setID(int id);

void setAddress(string address);

string getName();

int getID();

string getAddress();

void print(); // outPutResult

private:

string Name;

int ID;

string Address;

};

? Person.cpp

#include "Person.h"

using namespace std;

Person::Person()

{

Name = "S.M.Wang";

ID = 070145;

Address = "蓮花路200號";

}

Person::Person(string name, int id, string address)

{

setPerson(name, id, address);

}

Person::~Person()

{

cout << "object Destructor is called" << endl;

}

void Person::setPerson(string name, int id, string address)

{

Name = name;

ID = id;

Address = address;

}

void Person::setName(string name)

{

Name = name;

}

void Person::setID(int id)

{

ID = id;

}

void Person::setAddress(string address)

{

Address = address;

}

string Person::getName()

{

return Name;

}

int Person::getID()

{

return ID;

}

string Person::getAddress()

{

return Address;

}

void Person::print()

{

cout << "姓名:" << getName() << endl;

cout << "ID:" << getID() << endl;

cout << "住址:" << getAddress() << endl;

}

? 結(jié)果如下:

請輸入姓名:王小明

請輸入ID:22104070

請輸入住址:蓮花路200號

姓名:王小明

ID:22104070

住址:蓮花路200號

object Destructor is called

Process returned 0 (0x0) execution time : 15.911 s

Press any key to continue.

4.3 C++對象模型和this指針

4.3.1 成員變量和成員函數(shù)分開存儲

在C++中,類內(nèi)的成員變量和成員函數(shù)分開存儲。 只有非靜態(tài)成員變量才屬于類的對象上。

? 例4.3.1

#include

using namespace std;

class Person

{

public:

Person()

{

mA = 0;

}

//非靜態(tài)成員變量占對象空間

int mA;

//靜態(tài)成員變量不占對象空間

static int mB;

//函數(shù)也不占對象空間,所有函數(shù)共享一個函數(shù)實例

void func()

{

cout << "mA:" << this->mA << endl;

}

//靜態(tài)成員函數(shù)也不占對象空間

static void sfunc()

{

}

};

int main()

{

cout << sizeof(Person) << endl;

return 0;

}

? 結(jié)果如下:

4

Process returned 0 (0x0) execution time : 0.013 s

Press any key to continue.

4.3.2 this指針概念

? c++通過提供特殊的對象指針,this指針,解決區(qū)分對象調(diào)用自己的問題。this指針指向被調(diào)用的成員函數(shù)所屬的對象。

? 指針是隱含每一個非靜態(tài)成員函數(shù)內(nèi)的一種指針。

? this指針不需要定義,直接使用即可。

? this指針的用途:

當(dāng)形參和成員變量同名時,可用this指針來區(qū)分。在類的非靜態(tài)成員函數(shù)中返回對象本身,可使用return *this。

? 例4.3.2

#include

using namespace std;

class Person

{

public:

Person(int age)

{

//1、當(dāng)形參和成員變量同名時,可用this指針來區(qū)分

this->age = age;

}

Person& PersonAddPerson(Person p)

{

this->age += p.age;

//返回對象本身

return *this;

}

int age;

};

void test01()

{

Person p1(10);

cout << "p1.age = " << p1.age << endl;

Person p2(10);

p2.PersonAddPerson(p1).PersonAddPerson(p1).PersonAddPerson(p1);

cout << "p2.age = " << p2.age << endl;

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

p1.age = 10

p2.age = 40

Process returned 0 (0x0) execution time : 0.026 s

Press any key to continue.

4.3.3 空指針訪問成員函數(shù)

C++中空指針也是可以調(diào)用成員函數(shù)的,但是也要注意有沒有用到this指針。 如果用到this指針,需要加以判斷保證代碼的健壯性。

? 例4.3.3

#include

using namespace std;

//空指針訪問成員函數(shù)

class Person

{

public:

void ShowClassName()

{

cout << "我是Person類!" << endl;

}

void ShowPerson()

{

if (this == NULL)

{

return;

}

cout << mAge << endl;

}

public:

int mAge;

};

void test01()

{

Person * p = NULL;

p->ShowClassName(); //空指針,可以調(diào)用成員函數(shù)

p->ShowPerson(); //但是如果成員函數(shù)中用到了this指針,就不可以了

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

我是Person類!

Process returned 0 (0x0) execution time : 0.003 s

Press any key to continue.

4.3.4 const修飾成員函數(shù)

? 常函數(shù):

成員函數(shù)后加const后我們稱為這個函數(shù)為常函數(shù)。常函數(shù)內(nèi)不可以修改成員屬性。成員屬性聲明時加關(guān)鍵字mutable后,在常函數(shù)中依然可以修改。

? 常對象:

聲明對象前加const稱該對象為常對象。常對象只能調(diào)用常函數(shù)。

? 例4.3.4

#include

using namespace std;

class Person

{

public:

Person()

{

m_A = 0;

m_B = 0;

}

//this指針的本質(zhì)是一個指針常量,指針的指向不可修改

//如果想讓指針指向的值也不可以修改,需要聲明常函數(shù)

void ShowPerson() const

{

//const Type* const pointer;

//this = NULL; //不能修改指針的指向 Person* const this;

//this->mA = 100; //但是this指針指向的對象的數(shù)據(jù)是可以修改的

//const修飾成員函數(shù),表示指針指向的內(nèi)存空間的數(shù)據(jù)不能修改,除了mutable修飾的變量

this->m_B = 100;

}

void MyFunc() const

{

//mA = 10000;

}

public:

int m_A;

mutable int m_B; //可修改 可變的

};

//const修飾對象 常對象

void test01()

{

const Person person; //常量對象

cout << person.m_A << endl;

//person.mA = 100; //常對象不能修改成員變量的值,但是可以訪問

person.m_B = 100; //但是常對象可以修改mutable修飾成員變量

//常對象訪問成員函數(shù)

person.MyFunc(); //常對象不能調(diào)用const的函數(shù)

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

0

Process returned 0 (0x0) execution time : 0.008 s

Press any key to continue.

4.3.5 GradeBook類

? 題目如下:

? 上機(jī)實驗一,參考上課范例,完成 GradeBook 類(class)設(shè)計。

? 將類定義(class definition)寫在 GradeBook.h 中。 將成員函數(shù)(member function)寫在 GradeBook.cpp 中。編程一個主程序(main)創(chuàng)建兩個 GradeBook 對象,測試類的所有成員函數(shù)。

? GradeBook

-courseName: string //at most 25 characters

-studentCount : int //number of student

-grade: double[] //double array to hold student grades

+setCourseName(name:string)

+setStudentCount(id : int)

+getCourseName():string

+getStudentCount():int

+print() //to display information of GradeBook object

? 程序接口示范

? 編程設(shè)計者 王小明 221040700101 ? 請輸入課程名稱:Object Oriented Programming ? 請輸入學(xué)生人數(shù): 120 ? 利用 getCourseName 以及 getStudentCount 顯示第一個對象的信息: ? 課程名稱:Object Oriented Programming ? 學(xué)生人數(shù): 120 ? 請輸入課程名稱:Linear Algebra ? 請輸入學(xué)生人數(shù): 125 ? 利用 print 顯示第二個對象的信息: ? 課程名稱:Linear Algebra ? 學(xué)生人數(shù): 125

? 解答如下:

? main.cpp

#include

#include "Person.h"

using namespace std;

int main()

{

Person myPerson;

// Person myPerson("S.M.Wang", 070145, "蓮花路200號");

cout << "請輸入姓名:" ;

string name;

cin >> name;

cout << "請輸入ID:" ;

int id;

cin >> id;

cout << "請輸入住址:" ;

string address;

cin >> address;

myPerson.setName(name);

myPerson.setID(id);

myPerson.setAddress(address);

myPerson.print();

return 0;

}

Person.h

#include

using namespace std;

class Person

{

public:

Person();

Person(string name, int id, string address);

~Person();

void setPerson(string name, int id, string address);

void setName(string name);

void setID(int id);

void setAddress(string address);

string getName();

int getID();

string getAddress();

void print(); // outPutResult

private:

string Name;

int ID;

string Address;

};

Person.cpp

#include "Person.h"

using namespace std;

Person::Person()

{

Name = "S.M.Wang";

ID = 070145;

Address = "蓮花路200號";

}

Person::Person(string name, int id, string address)

{

setPerson(name, id, address);

}

Person::~Person()

{

cout << "object Destructor is called" << endl;

}

void Person::setPerson(string name, int id, string address)

{

Name = name;

ID = id;

Address = address;

}

void Person::setName(string name)

{

Name = name;

}

void Person::setID(int id)

{

ID = id;

}

void Person::setAddress(string address)

{

Address = address;

}

string Person::getName()

{

return Name;

}

int Person::getID()

{

return ID;

}

string Person::getAddress()

{

return Address;

}

void Person::print()

{

cout << "姓名:" << getName() << endl;

cout << "ID:" << getID() << endl;

cout << "住址:" << getAddress() << endl;

}

結(jié)果如下:

請輸入姓名:S.M.Wang

請輸入ID:070145

請輸入住址:蓮花路200號

姓名:S.M.Wang

ID:70145

住址:蓮花路200號

object Destructor is called

Process returned 0 (0x0) execution time : 27.263 s

Press any key to continue.

4.4 友元

? 生活中你的家有客廳(Public),有你的臥室(Private)。

? 客廳所有來的客人都可以進(jìn)去,但是你的臥室是私有的,也就是說只有你能進(jìn)去。

? 但是呢,你也可以允許你的好閨蜜好基友進(jìn)去。

? 在程序里,有些私有屬性 也想讓類外特殊的一些函數(shù)或者類進(jìn)行訪問,就需要用到友元的技術(shù)。

? 友元的目的就是讓一個函數(shù)或者類 訪問另一個類中私有成員。

? 友元的關(guān)鍵字為 friend

? 友元的三種實現(xiàn)

全局函數(shù)做友元類做友元成員函數(shù)做友元

4.4.1 全局函數(shù)做友元

? 例4.4.1

#include

using namespace std;

class Building

{

//告訴編譯器 goodGay全局函數(shù) 是 Building類的好朋友,可以訪問類中的私有內(nèi)容

friend void goodGay(Building * building);

public:

Building()

{

this->m_SittingRoom = "客廳";

this->m_BedRoom = "臥室";

}

public:

string m_SittingRoom; //客廳

private:

string m_BedRoom; //臥室

};

void goodGay(Building * building)

{

cout << "好基友正在訪問: " << building->m_SittingRoom << endl;

cout << "好基友正在訪問: " << building->m_BedRoom << endl;

}

void test01()

{

Building b;

goodGay(&b);

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

好基友正在訪問: 客廳

好基友正在訪問: 臥室

Process returned 0 (0x0) execution time : 0.032 s

Press any key to continue.

4.4.2 類做友元

? 例4.4.2

#include

using namespace std;

class Building;

class goodGay

{

public:

goodGay();

void visit();

private:

Building *building;

};

class Building

{

//告訴編譯器 goodGay類是Building類的好朋友,可以訪問到Building類中私有內(nèi)容

friend class goodGay;

public:

Building();

public:

string m_SittingRoom; //客廳

private:

string m_BedRoom;//臥室

};

Building::Building()

{

this->m_SittingRoom = "客廳";

this->m_BedRoom = "臥室";

}

goodGay::goodGay()

{

building = new Building;

}

void goodGay::visit()

{

cout << "好基友正在訪問" << building->m_SittingRoom << endl;

cout << "好基友正在訪問" << building->m_BedRoom << endl;

}

void test01()

{

goodGay gg;

gg.visit();

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

好基友正在訪問客廳

好基友正在訪問臥室

Process returned 0 (0x0) execution time : 0.009 s

Press any key to continue.

4.4.3 成員函數(shù)做友元

? 例4.4.3

#include

using namespace std;

class Building;

class goodGay

{

public:

goodGay();

void visit(); //只讓visit函數(shù)作為Building的好朋友,可以發(fā)訪問Building中私有內(nèi)容

void visit2();

private:

Building *building;

};

class Building

{

//告訴編譯器 goodGay類中的visit成員函數(shù) 是Building好朋友,可以訪問私有內(nèi)容

friend void goodGay::visit();

public:

Building();

public:

string m_SittingRoom; //客廳

private:

string m_BedRoom;//臥室

};

Building::Building()

{

this->m_SittingRoom = "客廳";

this->m_BedRoom = "臥室";

}

goodGay::goodGay()

{

building = new Building;

}

void goodGay::visit()

{

cout << "好基友正在訪問" << building->m_SittingRoom << endl;

cout << "好基友正在訪問" << building->m_BedRoom << endl;

}

void goodGay::visit2()

{

cout << "好基友正在訪問" << building->m_SittingRoom << endl;

//cout << "好基友正在訪問" << building->m_BedRoom << endl;

}

void test01()

{

goodGay gg;

gg.visit();

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

好基友正在訪問客廳

好基友正在訪問臥室

Process returned 0 (0x0) execution time : 0.013 s

Press any key to continue.

4.4.4 Date類作為person類的友元

? 題目如下:

? 上機(jī)實驗三,沿用上機(jī)實驗二的Person類,設(shè)計一個Date類,并在Person中增加Date的對象Birthday(has a)。將類定義(class definition)寫在 Person.h 及 Date.h 中。 將成員函數(shù)(member function)寫在 person.cpp 及 Date.cpp中。 ? 編程一個主程式(main) 在主程序中建構(gòu)兩個 Person 對象,一個用全預(yù)設(shè)值,另一個給定所有的參數(shù)。 測試所有的功能,打?。╬rint())對象的內(nèi)容。 ? Date

<>+Date(y : int = 0, m : int = 0,d : int = 0)

<>+~Date()

+setYear(y : int) : void

+setMonth(m : int) : void

+setDay(d : int) : void

+getYear() : int

+getMonth() : int

+getDay() : int

+print() : void

-Year : int

-Month : int

-Day : int

? Person

-Name : string

-ID : int

-Address : string

-Birthday: Date

<> +Person(name : string = “”, id : int =

0, address : string = “”, Date = Date())

<> +~Person()

+setName(name : string)

+getName() : string

+setID(id : int)

+getID() : int

+setAddress(address : string)

+getAddress() : string

+setBirthday(d : Date)

+getBirthday() : Date

+print() : void

? 解答如下:

? main.cpp

#include

#include "Person.h"

using namespace std;

int main()

{

Person myPerson;

// Person myPerson("S.M.Wang", 070145, "蓮花路200號");

cout << "請輸入姓名:" ;

string name;

cin >> name;

cout << "請輸入ID:" ;

int id;

cin >> id;

cout << "請輸入住址:" ;

string address;

cin >> address;

Date myDate;

cout << "請輸入生日年:" ;

int year;

cin >> year;

cout << "請輸入生日月:" ;

int month;

cin >> month;

cout << "請輸入生日天:" ;

int day;

cin >> day;

myPerson.setName(name);

myPerson.setID(id);

myPerson.setAddress(address);

myDate.setYear(year);

myDate.setMonth(month);

myDate.setDay(day);

myPerson.setBirthday(myDate); // 調(diào)用的形參為類

myPerson.print();

return 0;

}

? Person.h

#include

#include "Date.h"

using namespace std;

class Person

{

public:

Person();

Person(string name, int id, string address);

~Person();

void setPerson(string name, int id, string address);

void setName(string name);

void setID(int id);

void setAddress(string address);

void setBirthday(Date d);

string getName();

int getID();

string getAddress();

Date getBirthday();

void print(); // outPutResult

private:

string Name;

int ID;

string Address;

Date Birthday;

};

? Date.h

#include

using namespace std;

class Date

{

friend class Person;

public:

Date();

Date(int y, int m, int d);

~Date();

void setYear(int y);

void setMonth(int m);

void setDay(int d);

int getYear();

int getMonth();

int getDay();

void print();

private:

int Year;

int Month;

int Day;

};

? Person.cpp

#include "Person.h"

#include

using namespace std;

Person::Person()

{

Name = "S.M.Wang";

ID = 070145;

Address = "蓮花路200號";

}

Person::Person(string name, int id, string address)

{

setPerson(name, id, address);

}

Person::~Person()

{

//cout << "object Destructor is called" << endl;

}

void Person::setPerson(string name, int id, string address)

{

Name = name;

ID = id;

Address = address;

}

void Person::setName(string name)

{

Name = name;

}

void Person::setID(int id)

{

ID = id;

}

void Person::setAddress(string address)

{

Address = address;

}

string Person::getName()

{

return Name;

}

int Person::getID()

{

return ID;

}

string Person::getAddress()

{

return Address;

}

void Person::setBirthday(Date d) // 調(diào)用的形參是類

{

Birthday = d;

}

Date Person::getBirthday() // 返回的是類

{

return Birthday;

}

void Person::print()

{

cout << "Name:" << getName() << endl;

cout << "ID:" << getID() << endl;

cout << "Address:" << getAddress() << endl;

cout << "Birthday:" << getBirthday().getYear(); // getBirthday()返回的是類,再調(diào)用類中的子函數(shù)滿足cout的返回值。

cout << " " << getBirthday().getMonth();

cout << " " << getBirthday().getDay() << endl;

}

? Date.cpp

#include "Date.h"

#include

using namespace std;

Date::Date()

{

Year = 0;

Month = 0;

Day = 0;

}

Date::Date(int year, int month, int day)

{

setYear(year);

setMonth(month);

setDay(day);

}

Date::~Date()

{

//cout << "object Destructor is called" << endl;

}

void Date::setYear(int year)

{

Year = year;

}

void Date::setMonth(int month)

{

Month = month;

}

void Date::setDay(int day)

{

Day = day;

}

int Date::getYear()

{

return Year;

}

int Date::getMonth()

{

return Month;

}

int Date::getDay()

{

return Day;

}

void Date::print()

{

cout << "Year :" << getYear() << endl;

cout << "Month :" << getMonth() << endl;

cout << "Day :" << getDay() << endl;

}

? 結(jié)果如下:

請輸入姓名:S.M.Wang

請輸入ID:070145

請輸入住址:蓮花路200號

請輸入生日年:2000

請輸入生日月:1

請輸入生日天:1

Name:S.M.Wang

ID:70145

Address:蓮花路200號

Birthday:2000 1 1

Process returned 0 (0x0) execution time : 49.737 s

Press any key to continue.

4.5 運算符重載

? 運算符重載概念:對已有的運算符重新進(jìn)行定義,賦予其另一種功能,以適應(yīng)不同的數(shù)據(jù)類型。

4.5.1 加號運算符重載

? 作用:實現(xiàn)兩個自定義數(shù)據(jù)類型相加的運算。

? 例4.5.1

#include

using namespace std;

class Person

{

public:

Person() {};

Person(int a, int b)

{

this->m_A = a;

this->m_B = b;

}

//成員函數(shù)實現(xiàn) + 號運算符重載

Person operator+(const Person& p)

{

Person temp;

temp.m_A = this->m_A + p.m_A;

temp.m_B = this->m_B + p.m_B;

return temp;

}

public:

int m_A;

int m_B;

};

//全局函數(shù)實現(xiàn) + 號運算符重載

//Person operator+(const Person& p1, const Person& p2)

//{

// Person temp(0, 0);

// temp.m_A = p1.m_A + p2.m_A;

// temp.m_B = p1.m_B + p2.m_B;

// return temp;

//}

//運算符重載 可以發(fā)生函數(shù)重載

Person operator+(const Person& p2, int val)

{

Person temp;

temp.m_A = p2.m_A + val;

temp.m_B = p2.m_B + val;

return temp;

}

void test()

{

Person p1(10, 10);

Person p2(20, 20);

//成員函數(shù)方式

Person p3 = p2 + p1; //相當(dāng)于 p2.operaor+(p1)

cout << "mA:" << p3.m_A << " mB:" << p3.m_B << endl;

Person p4 = p3 + 10; //相當(dāng)于 operator+(p3,10)

cout << "mA:" << p4.m_A << " mB:" << p4.m_B << endl;

}

int main()

{

test();

return 0;

}

? 結(jié)果如下:

mA:30 mB:30

mA:40 mB:40

Process returned 0 (0x0) execution time : 0.179 s

Press any key to continue.

對于內(nèi)置的數(shù)據(jù)類型的表達(dá)式的的運算符是不可能改變的。

不要濫用運算符重載。

4.5.2 左移運算符重載

? 作用:重載左移運算符配合友元可以實現(xiàn)輸出自定義數(shù)據(jù)類型。

? 例4.5.2

#include

using namespace std;

class Person

{

friend ostream& operator<<(ostream& out, Person& p);

public:

Person(int a, int b)

{

this->m_A = a;

this->m_B = b;

}

//成員函數(shù) 實現(xiàn)不了 p << cout 不是我們想要的效果

//void operator<<(Person& p)

//{

//

//}

private:

int m_A;

int m_B;

};

//全局函數(shù)實現(xiàn)左移重載

//ostream對象只能有一個

ostream& operator<<(ostream& out, Person& p)

{

out << "a:" << p.m_A << " b:" << p.m_B;

return out;

}

void test()

{

Person p1(10, 20);

cout << p1 << '\n' << "hello world" << endl; //鏈?zhǔn)骄幊?/p>

}

int main()

{

test();

return 0;

}

? 結(jié)果如下:

a:10 b:20

hello world

Process returned 0 (0x0) execution time : 0.007 s

Press any key to continue.

4.5.3 遞增運算符重載

? 作用:

通過重載遞增運算符,實現(xiàn)自己的整型數(shù)據(jù)。前置遞增返回引用,后置遞增返回值。

? 例4.5.3

#include

using namespace std;

class MyInteger

{

friend ostream& operator<<(ostream& out, MyInteger myint);

public:

MyInteger()

{

m_Num = 0;

}

//前置++

MyInteger& operator++()

{

//先++

m_Num++;

//再返回

return *this;

}

//后置++

MyInteger operator++(int)

{

//先返回

MyInteger temp = *this; //記錄當(dāng)前本身的值,然后讓本身的值加1,但是返回的是以前的值,達(dá)到先返回后++;

m_Num++;

return temp;

}

private:

int m_Num;

};

ostream& operator<<(ostream& out, MyInteger myint)

{

out << myint.m_Num;

return out;

}

//前置++ 先++ 再返回

void test01()

{

MyInteger myInt;

cout << ++myInt << endl;

cout << myInt << endl;

}

//后置++ 先返回 再++

void test02()

{

MyInteger myInt;

cout << myInt++ << endl;

cout << myInt << endl;

}

int main()

{

test01();

test02();

return 0;

}

? 結(jié)果如下:

1

1

0

1

Process returned 0 (0x0) execution time : 0.007 s

Press any key to continue.

4.5.4 賦值運算符重載

? c++編譯器至少給一個類添加4個函數(shù)

默認(rèn)構(gòu)造函數(shù)(無參,函數(shù)體為空)默認(rèn)析構(gòu)函數(shù)(無參,函數(shù)體為空)默認(rèn)拷貝構(gòu)造函數(shù),對屬性進(jìn)行值拷貝賦值運算符 operator=, 對屬性進(jìn)行值拷貝

? 如果類中有屬性指向堆區(qū),做賦值操作時也會出現(xiàn)深淺拷貝問題。

? 例4.5.4

#include

using namespace std;

class Person

{

public:

Person(int age)

{

//將年齡數(shù)據(jù)開辟到堆區(qū)

m_Age = new int(age);

}

//重載賦值運算符

Person& operator=(Person &p)

{

if (m_Age != NULL)

{

delete m_Age;

m_Age = NULL;

}

//編譯器提供的代碼是淺拷貝

//m_Age = p.m_Age;

//提供深拷貝 解決淺拷貝的問題

m_Age = new int(*p.m_Age);

//返回自身

return *this;

}

~Person()

{

if (m_Age != NULL)

{

delete m_Age;

m_Age = NULL;

}

}

//年齡的指針

int *m_Age;

};

void test01()

{

Person p1(18);

Person p2(20);

Person p3(30);

p3 = p2 = p1; //賦值操作

cout << "p1的年齡為:" << *p1.m_Age << endl;

cout << "p2的年齡為:" << *p2.m_Age << endl;

cout << "p3的年齡為:" << *p3.m_Age << endl;

}

int main()

{

test01();

//int a = 10;

//int b = 20;

//int c = 30;

//c = b = a;

//cout << "a = " << a << endl;

//cout << "b = " << b << endl;

//cout << "c = " << c << endl;

return 0;

}

? 結(jié)果如下:

p1的年齡為:18

p2的年齡為:18

p3的年齡為:18

Process returned 0 (0x0) execution time : 0.109 s

Press any key to continue.

4.5.5 關(guān)系運算符重載

? 作用: 重載關(guān)系運算符,可以讓兩個自定義類型對象進(jìn)行對比操作。

? 例4.5.5

#include

using namespace std;

class Person

{

public:

Person(string name, int age)

{

this->m_Name = name;

this->m_Age = age;

};

bool operator==(Person & p)

{

if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)

{

return true;

}

else

{

return false;

}

}

bool operator!=(Person & p)

{

if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)

{

return false;

}

else

{

return true;

}

}

string m_Name;

int m_Age;

};

void test01()

{

//int a = 0;

//int b = 0;

Person a("孫悟空", 18);

Person b("孫悟空", 20);

if (a == b)

{

cout << "a和b相等" << endl;

}

else

{

cout << "a和b不相等" << endl;

}

/*if (a != b)

{

cout << "a和b不相等" << endl;

}

else

{

cout << "a和b相等" << endl;

}*/

}

int main()

{

test01();

return 0;

}

? 例4.5.5

a和b不相等

Process returned 0 (0x0) execution time : 0.060 s

Press any key to continue.

4.5.6 函數(shù)調(diào)用運算符重載

函數(shù)調(diào)用運算符 () 也可以重載。由于重載后使用的方式非常像函數(shù)的調(diào)用,因此稱為仿函數(shù)。仿函數(shù)沒有固定寫法,非常靈活。

? 例4.5.6

#include

using namespace std;

class MyPrint

{

public:

void operator()(string text)

{

cout << text << endl;

}

};

void test01()

{

//重載的()操作符 也稱為仿函數(shù)

MyPrint myFunc;

myFunc("hello world");

}

class MyAdd

{

public:

int operator()(int v1, int v2)

{

return v1 + v2;

}

};

void test02()

{

MyAdd add;

int ret = add(10, 10);

cout << "ret = " << ret << endl;

//匿名對象調(diào)用

cout << "MyAdd()(100,100) = " << MyAdd()(100, 100) << endl;

}

int main()

{

test01();

test02();

return 0;

}

? 結(jié)果如下:

hello world

ret = 20

MyAdd()(100,100) = 200

Process returned 0 (0x0) execution time : 0.052 s

Press any key to continue.

4.5.7 重載+, - ,*, /, >>,<<運算符

? 題目如下:

? 上機(jī)實驗四設(shè)計一個 Complex 類,并在 Complex 中重載+, - ,*, /, >>以及<<等運算符。

建構(gòu)數(shù)個 Complex 物件,測試對象的所有成員函數(shù)(member functions)。建構(gòu)數(shù)個 Complex 物件的指針(pointer),以指針測試物件的所有成員函數(shù)(member functions)。

? Complex

-Real : double

-Imaginary : double

<> +Complex(real : double = 0.0,

imaginary : double = 0.0)

<> +~Complex()

+setReal(real : double)

+getReal() : double

+setImaginary(imaginary : double)

+getImaginary() : double

+operator+(c: Complex) : Complex &

+operator-(c: Complex) : Complex &

+operator*(c: Complex) : Complex &

+operator/(c: Complex) : Complex &

<>+operator>>(input : istream&, c :

&Complex) : istream&

<>+operator<<(output : ostream&, c :

Complex) : ostream&

? 解答如下:

? main.cpp

#include

#include "Complex.h"

using namespace std;

int main()

{

Complex c1(3.0, 4.0);

Complex c2(4.0, 5.0);

Complex c3;

Complex c4;

Complex c5;

Complex c6;

c3 = c1 + c2;

c4 = c1 - c2;

c5 = c1 * c2;

c6 = c1 / c2;

cout << "c1 = " << c1 << endl;

cout << "c2 = " << c2 << endl;

cout << "c1 + c2 = " << c3 << endl;

cout << "c1 - c2 = " << c4 << endl;

cout << "c1 * c2 = " << c5 << endl;

cout << "c1 / c2 = " << c6 << endl;

Complex *ptr1;

Complex *ptr2;

Complex *ptr3;

Complex *ptr4;

Complex *ptr5;

Complex *ptr6;

ptr1 = new Complex(7.0, 8.0);

ptr2 = new Complex(6.0, 5.0);

ptr3 = new Complex();

ptr4 = new Complex();

ptr5 = new Complex();

ptr6 = new Complex();

*ptr3 = *ptr1 + *ptr2;

*ptr4 = *ptr1 - *ptr2;

*ptr5 = *ptr1 * *ptr2;

*ptr6 = *ptr1 / *ptr2;

cout << "*ptr1 = " << *ptr1 << endl;

cout << "*ptr2 = " << *ptr2 << endl;

cout << "*ptr1 + *ptr2 = " << *ptr3 << endl;

cout << "*ptr1 - *ptr2 = " << *ptr4 << endl;

cout << "*ptr1 * *ptr2 = " << *ptr5 << endl;

cout << "*ptr1 / *ptr2 = " << *ptr6 << endl;

delete ptr3;

delete ptr4;

delete ptr5;

delete ptr6;

return 0;

}

? Complex.h

#ifndef COMPLEX_H

#define COMPLEX_H

#include

using namespace std;

class Complex

{

public:

Complex();

Complex(double real, double imaginary); // default constructor

~Complex();

void setReal(double real);

void setImaginary(double imaginary);

double getReal();

double getImaginary();

Complex operator+(const Complex& c); // 重載

Complex operator-(const Complex& c); //

Complex operator*(const Complex& c); //

Complex operator/(const Complex& c); //

friend istream& operator>>(istream& input, Complex& a);

friend ostream& operator<<(ostream& output, Complex& a);

void print(); // in real + i imaginary

private:

double Real;

double Imaginary;

};

#endif // COMPLEX_H

? Complex.cpp

#include "Complex.h"

using namespace std;

Complex::Complex()

{

Real = 0.0;

Imaginary = 0.0;

}

Complex::Complex(double real, double imaginary)

{

setReal(real);

setImaginary(imaginary);

}

Complex::~Complex()

{

//cout << "object Destructor is called" << endl;

}

void Complex::setReal(double real)

{

Real = real;

}

void Complex::setImaginary(double imaginary)

{

Imaginary = imaginary;

}

double Complex::getReal()

{

return Real;

}

double Complex::getImaginary()

{

return Imaginary;

}

Complex Complex::operator+(const Complex& c)

{

return Complex(getReal() + c.Real, getImaginary() + c.Imaginary);

}

Complex Complex::operator-(const Complex& c)

{

return Complex(getReal() - c.Real, getImaginary() - c.Imaginary);

}

Complex Complex::operator*(const Complex& c)

{

return Complex(getReal() * c.Real - getImaginary() * c.Imaginary, getReal() * c.Imaginary + getImaginary() * c.Real);

}

Complex Complex::operator/(const Complex& c)

{

double denominator = c.Real * c.Real + c.Imaginary * c.Imaginary;

double a = getReal() * c.Real + getImaginary() * c.Imaginary;

double b = getImaginary() * c.Real - getReal() * c.Imaginary;

return Complex(a / denominator, b / denominator);

}

// 重載輸入運算符

istream& operator>>(istream& input, Complex& c)

{

input >> c.Real >> c.Imaginary;

return input;

}

// 重載輸出運算符

ostream& operator<<(ostream& output, Complex& c)

{

output << c.getReal() << "+" << c.getImaginary() << "i";

return output;

}

void Complex::print()

{

cout << "Real is " << getReal() << endl;

cout << "Imaginary is " << getImaginary() << endl;

cout << endl;

}

? 結(jié)果如下:

c1 = 3+4i

c2 = 4+5i

c1 + c2 = 7+9i

c1 - c2 = -1+-1i

c1 * c2 = -8+31i

c1 / c2 = 0.780488+0.0243902i

*ptr1 = 7+8i

*ptr2 = 6+5i

*ptr1 + *ptr2 = 13+13i

*ptr1 - *ptr2 = 1+3i

*ptr1 * *ptr2 = 2+83i

*ptr1 / *ptr2 = 1.34426+0.213115i

Process returned 0 (0x0) execution time : 0.070 s

Press any key to continue.

4.6 繼承

? 繼承是面向?qū)ο笕筇匦灾?/p>

? 我們發(fā)現(xiàn),定義這些類時,下級別的成員除了擁有上一級的共性,還有自己的特性。

? 這個時候我們就可以考慮利用繼承的技術(shù),減少重復(fù)代碼。

4.6.1 繼承的基本語法

class 子類 : 繼承方式 父類

{

...

}

? 繼承的好處

? 1.可以減少重復(fù)的代碼。

? 2.在父類中體現(xiàn)共性,在子類中體現(xiàn)特性。

? 例4.6.1.1 普通實現(xiàn)

#include

using namespace std;

class Java

{

public:

void header()

{

cout << "首頁,公開課,登錄,注冊...(公共頭部)" << endl;

}

void footer()

{

cout << "幫助中心,交流合作,站內(nèi)地圖...(公共底部)" << '\n' << endl;

}

void left()

{

cout << "Java, Python, C++, ...(公共分類列表)" << endl;

}

void content()

{

cout << '\n' << "Java學(xué)習(xí)資料" << '\n' << endl;

}

};

class CPP

{

public:

void header()

{

cout << "首頁,公開課,登錄,注冊...(公共頭部)" << endl;

}

void footer()

{

cout << "幫助中心,交流合作,站內(nèi)地圖...(公共底部)" << '\n' << endl;

}

void left()

{

cout << "Java, Python, C++, ...(公共分類列表)" << endl;

}

void content()

{

cout << '\n' << "C++學(xué)習(xí)資料" << '\n' << endl;

}

};

class Python

{

public:

void header()

{

cout << "首頁,公開課,登錄,注冊...(公共頭部)" << endl;

}

void footer()

{

cout << "幫助中心,交流合作,站內(nèi)地圖...(公共底部)" << '\n' << endl;

}

void left()

{

cout << "Java, Python, C++, ...(公共分類列表)" << endl;

}

void content()

{

cout << '\n' << "Python學(xué)習(xí)資料" << '\n' << endl;

}

};

void test01()

{

Java ja;

ja.header();

ja.left();

ja.content();

ja.footer();

}

void test02()

{

Python py;

py.header();

py.left();

py.content();

py.footer();

}

void test03()

{

CPP cpp;

cpp.header();

cpp.left();

cpp.content();

cpp.footer();

}

int main()

{

test01();

test02();

test03();

return 0;

}

? 例4.6.1.2 繼承實現(xiàn)

#include

using namespace std;

class BasePage

{

public:

void header()

{

cout << "首頁,公開課,登錄,注冊...(公共頭部)" << endl;

}

void footer()

{

cout << "幫助中心,交流合作,站內(nèi)地圖...(公共底部)" << '\n' << endl;

}

void left()

{

cout << "Java, Python, C++, ...(公共分類列表)" << endl;

}

};

class Java : public BasePage

{

public:

void content()

{

cout << '\n' << "Java學(xué)習(xí)資料" << '\n' << endl;

}

};

class CPP : public BasePage

{

public:

void content()

{

cout << '\n' << "C++學(xué)習(xí)資料" << '\n' << endl;

}

};

class Python : public BasePage

{

public:

void content()

{

cout << '\n' << "Python學(xué)習(xí)資料" << '\n' << endl;

}

};

void test01()

{

Java ja;

ja.header();

ja.left();

ja.content();

ja.footer();

}

void test02()

{

Python py;

py.header();

py.left();

py.content();

py.footer();

}

void test03()

{

CPP cpp;

cpp.header();

cpp.left();

cpp.content();

cpp.footer();

}

int main()

{

test01();

test02();

test03();

return 0;

}

? 結(jié)果如下:

首頁,公開課,登錄,注冊...(公共頭部)

Java, Python, C++, ...(公共分類列表)

Java學(xué)習(xí)資料

幫助中心,交流合作,站內(nèi)地圖...(公共底部)

首頁,公開課,登錄,注冊...(公共頭部)

Java, Python, C++, ...(公共分類列表)

Python學(xué)習(xí)資料

幫助中心,交流合作,站內(nèi)地圖...(公共底部)

首頁,公開課,登錄,注冊...(公共頭部)

Java, Python, C++, ...(公共分類列表)

C++學(xué)習(xí)資料

幫助中心,交流合作,站內(nèi)地圖...(公共底部)

Process returned 0 (0x0) execution time : 0.201 s

Press any key to continue.

4.6.2 繼承方式

? 公共繼承? 保護(hù)繼承? 私有繼承

? 其都不能訪問父類中 private 的信息。

? 例4.6.2

#include

using namespace std;

class Base

{

public:

int m_A;

protected:

int m_B;

private:

int m_C;

};

//公共繼承

class Son1 :public Base

{

public:

void func()

{

m_A = 10; // 父類中的公共權(quán)限成員 到子類中仍然是公共權(quán)限

m_B = 10; // 父類中的保護(hù)權(quán)限成員 到子類中仍然是保護(hù)權(quán)限

//m_C = 10; // 父類中的私有權(quán)限成員 子類訪問不到

}

};

void test01()

{

Son1 s1;

s1.m_A = 100;

// s1.m_B = 100; // 到Son1中 m_B是保護(hù)權(quán)限 類外訪問不到

}

//保護(hù)繼承

class Son2 :protected Base

{

public:

void func()

{

m_A = 10; // 父類中的公共權(quán)限成員 到子類中變?yōu)楸Wo(hù)權(quán)限

m_B = 10; // 父類中的保護(hù)權(quán)限成員 到子類中仍然是保護(hù)權(quán)限

//m_C = 10; // 父類中的私有權(quán)限成員 子類訪問不到

}

};

void test02()

{

Son2 s2;

//s2.m_A = 100; // 在Son2中 m_A變?yōu)楸Wo(hù)權(quán)限,因此訪問不到。

}

//私有繼承

class Son3 :private Base

{

public:

void func()

{

m_A = 10; // 父類中的公共權(quán)限成員 到子類中變?yōu)樗接袡?quán)限

m_B = 10; // 父類中的保護(hù)權(quán)限成員 到子類中變?yōu)樗接袡?quán)限

//m_C = 10; // 父類中的私有權(quán)限成員 子類訪問不到

}

};

void test03()

{

Son3 s3;

//s3.m_A = 100; // 在Son3中 m_A變?yōu)樗接袡?quán)限,因此訪問不到。

}

int main()

{

test01();

test02();

test03();

return 0;

}

4.6.3 繼承中的對象模型

? 父類中私有成員也是被子類繼承下去了,只是由編譯器給隱藏后訪問不到。

? 例4.6.3

#include

using namespace std;

class Base

{

public:

int m_A;

protected:

int m_B;

private:

int m_C; //私有成員只是被隱藏了,但是還是會繼承下去

};

//公共繼承

class Son :public Base

{

public:

int m_D;

};

void test01()

{

cout << "sizeof Son = " << sizeof(Son) << endl;

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

sizeof Son = 16

Process returned 0 (0x0) execution time : 0.092 s

Press any key to continue.

4.6.4 繼承中構(gòu)造和析構(gòu)順序

? 繼承中 先調(diào)用父類構(gòu)造函數(shù),再調(diào)用子類構(gòu)造函數(shù),析構(gòu)順序與構(gòu)造相反。

? 例4.6.4

#include

using namespace std;

class Base

{

public:

Base()

{

cout << "Base構(gòu)造函數(shù)!" << endl;

}

~Base()

{

cout << "Base析構(gòu)函數(shù)!" << endl;

}

};

class Son : public Base

{

public:

Son()

{

cout << "Son構(gòu)造函數(shù)!" << endl;

}

~Son()

{

cout << "Son析構(gòu)函數(shù)!" << endl;

}

};

void test01()

{

//繼承中 先調(diào)用父類構(gòu)造函數(shù),再調(diào)用子類構(gòu)造函數(shù),析構(gòu)順序與構(gòu)造相反

Son s;

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

Base構(gòu)造函數(shù)!

Son構(gòu)造函數(shù)!

Son析構(gòu)函數(shù)!

Base析構(gòu)函數(shù)!

Process returned 0 (0x0) execution time : 0.084 s

Press any key to continue.

4.6.5 繼承同名成員處理方式

? 子類對象可以直接訪問到子類中同名成員。? 子類對象加作用域可以訪問到父類同名成員。? 當(dāng)子類與父類擁有同名的成員函數(shù),子類會隱藏父類中同名成員函數(shù),加作用域可以訪問到父類中同名函數(shù)。

? 例4.6.5.1 如果子類和父類成員同名,直接調(diào)用會調(diào)用到子類的數(shù)據(jù)。

#include

using namespace std;

//繼承中同名成員處理

class Base

{

public:

Base()

{

m_A = 100;

}

int m_A;

};

class Son :public Base

{

public:

Son()

{

m_A = 200;

}

int m_A;

};

void test01()

{

Son s;

cout << "m_A = " << s.m_A << endl;

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

m_A = 200

Process returned 0 (0x0) execution time : 0.061 s

Press any key to continue.

? 例4.6.5.2 如果子類和父類成員同名,前面加作用域( :: )調(diào)用會調(diào)用到父類的數(shù)據(jù)。

#include

using namespace std;

//繼承中同名成員處理

class Base

{

public:

Base()

{

m_A = 100;

}

int m_A;

};

class Son :public Base

{

public:

Son()

{

m_A = 200;

}

int m_A;

};

void test01()

{

Son s;

cout << "Son 下的 m_A = " << s.m_A << endl;

cout << "Base 下的 m_A = " << s.Base::m_A << endl;

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

Son 下的 m_A = 200

Base 下的 m_A = 100

Process returned 0 (0x0) execution time : 0.081 s

Press any key to continue.

4.6.6 繼承同名靜態(tài)成員處理方式

訪問子類同名成員 直接訪問即可。訪問父類同名成員 需要加作用域。

? 例4.6.6

#include

using namespace std;

class Base

{

public:

static void func()

{

cout << "Base - static void func()" << endl;

}

static void func(int a)

{

cout << "Base - static void func(int a)" << endl;

}

static int m_A;

};

int Base::m_A = 100;

class Son : public Base

{

public:

static void func()

{

cout << "Son - static void func()" << endl;

}

static int m_A;

};

int Son::m_A = 200;

//同名成員屬性

void test01()

{

//通過對象訪問

cout << "通過對象訪問: " << endl;

Son s;

cout << "Son 下 m_A = " << s.m_A << endl;

cout << "Base 下 m_A = " << s.Base::m_A << endl;

//通過類名訪問

cout << "通過類名訪問: " << endl;

cout << "Son 下 m_A = " << Son::m_A << endl;

cout << "Base 下 m_A = " << Son::Base::m_A << endl;

}

//同名成員函數(shù)

void test02()

{

//通過對象訪問

cout << "通過對象訪問: " << endl;

Son s;

s.func();

s.Base::func();

cout << "通過類名訪問: " << endl;

Son::func();

Son::Base::func();

//出現(xiàn)同名,子類會隱藏掉父類中所有同名成員函數(shù),需要加作作用域訪問

Son::Base::func(100);

}

int main()

{

//test01();

test02();

return 0;

}

? 結(jié)果如下:

通過對象訪問:

Son - static void func()

Base - static void func()

通過類名訪問:

Son - static void func()

Base - static void func()

Base - static void func(int a)

Process returned 0 (0x0) execution time : 0.109 s

Press any key to continue.

4.6.7 多繼承語法

? C++允許一個類繼承多個類。

? 語法如下:

class 子類 : 繼承方式 父類1, 繼承方式 父類2, ...

{

...

}

? 例4.6.7

#include

using namespace std;

class Base1

{

public:

Base1()

{

m_A = 100;

}

int m_A;

};

class Base2

{

public:

Base2()

{

m_B = 200;

}

int m_B;

};

// 子類 繼承Base1和Base2

class Son :public Base1, public Base2

{

public:

Son()

{

m_C = 300;

m_D = 400;

}

int m_C;

int m_D;

};

//多繼承容易產(chǎn)生成員同名的情況

//通過使用類名作用域可以區(qū)分調(diào)用哪一個基類的成員

void test01()

{

Son s;

cout << "sizeof Son = " << sizeof(s) << endl;

cout << s.Base1::m_A << endl;

cout << s.Base2::m_B << endl;

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

sizeof Son = 16

100

200

Process returned 0 (0x0) execution time : 0.039 s

Press any key to continue.

4.6.8 菱形繼承

? 菱形繼承概念:

兩個派生類繼承同一個基類。

又有某個類同時繼承者兩個派生類。

? 菱形繼承問題:

羊繼承了動物的數(shù)據(jù),駝同樣繼承了動物的數(shù)據(jù),當(dāng)草泥馬使用數(shù)據(jù)時,就會產(chǎn)生二義性。 草泥馬繼承自動物的數(shù)據(jù)繼承了兩份,其實我們應(yīng)該清楚,這份數(shù)據(jù)我們只需要一份就可以。

? 解決方法:

虛繼承

? 例4.6.8

#include

using namespace std;

class Animal

{

public:

int m_Age;

};

//繼承前加virtual關(guān)鍵字后,變?yōu)樘摾^承

//此時公共的父類Animal稱為虛基類

class Sheep : virtual public Animal {};

class Tuo : virtual public Animal {};

class SheepTuo : public Sheep, public Tuo {};

void test01()

{

SheepTuo st;

st.Sheep::m_Age = 100;

st.Tuo::m_Age = 200;

cout << "st.Sheep::m_Age = " << st.Sheep::m_Age << endl;

cout << "st.Tuo::m_Age = " << st.Tuo::m_Age << endl;

cout << "st.m_Age = " << st.m_Age << endl;

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

st.Sheep::m_Age = 200

st.Tuo::m_Age = 200

st.m_Age = 200

Process returned 0 (0x0) execution time : 0.129 s

Press any key to continue.

4.7 多態(tài)

4.7.1 多態(tài)的基本介紹

? 1.多態(tài)的基本語法

C++ 重寫:virtual 函數(shù)值返回類型 函數(shù)名 參數(shù)列表

2.多態(tài)滿足條件

有繼承關(guān)系子類重寫父類中的虛函數(shù)

? 3.多態(tài)使用條件

父類指針或引用指向子類對象

? 4.多態(tài)的優(yōu)點

代碼組織結(jié)構(gòu)清晰可讀性強(qiáng)利于前期和后期的擴(kuò)展以及維護(hù)

? 例4.7.1 class animal

#include

using namespace std;

// 多態(tài)

// 動物類

class Animal

{

public:

// 虛函數(shù)

virtual void speak()

{

cout << "動物在說話" << endl;

}

};

// 貓類

class Cat :public Animal

{

public:

// 重寫 函數(shù)返回值類型 函數(shù)名 參數(shù)列表 完全相同

virtual void speak()

{

cout << "小貓在說話" << endl;

}

};

// 狗類

class Dog :public Animal

{

public:

// 重寫 函數(shù)返回值類型 函數(shù)名 參數(shù)列表 完全相同

virtual void speak()

{

cout << "小狗在說話" << endl;

}

};

// 執(zhí)行說話的函數(shù)

// 地址早已綁定 在編譯階段確定函數(shù)地址

// 如果想執(zhí)行讓貓說話,那么這個函數(shù)不能提前綁定,要在運行階段進(jìn)行綁定,地址晚綁定

void doSpeak(Animal &animal) // Animal & animal == cat;

{

animal.speak();

}

void test01()

{

Cat cat;

doSpeak(cat);

Dog dog;

doSpeak(dog);

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

小貓在說話

小狗在說話

Process returned 0 (0x0) execution time : 0.085 s

Press any key to continue.

4.7.2 純虛函數(shù)和抽象類

? 在多態(tài)中,通常父類中的虛函數(shù)的實現(xiàn)是沒有意義的,主要是調(diào)用子類重寫的內(nèi)容,因此可以將虛函數(shù)改為純虛函數(shù)。

? 純虛函數(shù)的語法:

virtual 返回值類型 函數(shù)名 (形參列表) = 0;

? 當(dāng)類中有了純虛函數(shù),這個類也稱為抽象類。

? 抽象類的特點

無法實例化對象子類必須重寫抽象類中的純虛函數(shù),否則也屬于抽象類

? 例4.7.2

#include

using namespace std;

// 純虛函數(shù)和抽象類

class Base

{

public:

// 純虛函數(shù)

// 只要有一個純虛函數(shù),這個類稱為抽象類

// 抽象類的特點:

// 1.無法實例化對象

// 2.抽象類的子類 必須重寫父類中的純虛函數(shù),否則也屬于抽象類

virtual void func() = 0;

};

class Son :public Base

{

public:

virtual void func()

{

cout << "output the son result" << endl;

}

};

void test01()

{

// Base b; // 抽象類無法實例化對象

// new Base; // 抽象類無法實例化對象

Son s; // 子類必須重寫父類中的純虛函數(shù),否則無法實現(xiàn)實例化對象。

Base * base = new Son;

base->func();

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

output the son result

Process returned 0 (0x0) execution time : 0.083 s

Press any key to continue.

4.7.3 虛析構(gòu)和純虛析構(gòu)

? 多態(tài)使用時,如果子類中有屬性開辟到堆區(qū),那么父類指針在釋放的時候無法調(diào)用到子類的析構(gòu)代碼。

? 解決方式:將父類中的析構(gòu)函數(shù)改為虛析構(gòu)或者純虛析構(gòu)。

? 虛析構(gòu)和純虛析構(gòu)的共性:

可以解決父類指針釋放子類對象都需要有具體的函數(shù)實現(xiàn)

? 純虛析構(gòu)和虛析構(gòu)的區(qū)別:

如果是是純虛析構(gòu)函數(shù),該類屬于抽象類,無法實例化對象。

? 虛析構(gòu)語法:

c++ virtual ~類名() { ... }

? 純虛析構(gòu)的語法:

C++ virtual ~類名() = 0; 類名::類名() { ... }

? 例4.7.3.1 調(diào)用虛析構(gòu)函數(shù)

#include

#include

using namespace std;

// 虛析構(gòu)和純虛析構(gòu)

class Animal

{

public:

Animal()

{

cout << "Animal的構(gòu)造函數(shù)調(diào)用" << endl;

}

// 利用虛析構(gòu)函數(shù)可以解決父類指針釋放子類對象時不干凈的問題

virtual ~Animal()

{

cout << "Animal的虛析構(gòu)函數(shù)調(diào)用" << endl;

}

// 純虛析構(gòu) 需要聲明 需要實現(xiàn)

//virtual ~Animal() = 0;

// 純虛函數(shù)

virtual void speak() = 0;

};

/*Animal::~Animal()

{

cout << "Animal的純虛析構(gòu)函數(shù)調(diào)用" << endl;

}*/

class Cat :public Animal

{

public:

Cat(string name)

{

cout << "Cat的構(gòu)造函數(shù)調(diào)用" << endl;

m_Name = new string (name);

}

virtual void speak()

{

cout << *m_Name << "小貓在說話" << endl;

}

~Cat()

{

if (m_Name != NULL)

{

cout << "Cat的虛析構(gòu)函數(shù)調(diào)用" << endl;

delete m_Name;

m_Name = NULL;

}

}

string *m_Name;

};

void test01()

{

Animal * animal = new Cat("Tom");

animal->speak();

// 父類指針在析構(gòu)的時候 不會調(diào)用子類中的析構(gòu)函數(shù),導(dǎo)致子類如果有堆區(qū)屬性,出現(xiàn)內(nèi)存泄露

delete animal;

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

Animal的構(gòu)造函數(shù)調(diào)用

Cat的構(gòu)造函數(shù)調(diào)用

Tom小貓在說話

Cat的虛析構(gòu)函數(shù)調(diào)用

Animal的虛析構(gòu)函數(shù)調(diào)用

Process returned 0 (0x0) execution time : 0.113 s

Press any key to continue.

? 例4.7.3.2 調(diào)用純虛析構(gòu)函數(shù)

#include

#include

using namespace std;

// 虛析構(gòu)和純虛析構(gòu)

class Animal

{

public:

Animal()

{

cout << "Animal的構(gòu)造函數(shù)調(diào)用" << endl;

}

// 利用虛析構(gòu)函數(shù)可以解決父類指針釋放子類對象時不干凈的問題

/*virtual ~Animal()

{

cout << "Animal的虛析構(gòu)函數(shù)調(diào)用" << endl;

}*/

// 純虛析構(gòu) 需要聲明 需要實現(xiàn)

virtual ~Animal() = 0;

// 純虛函數(shù)

virtual void speak() = 0;

};

Animal::~Animal()

{

cout << "Animal的純虛析構(gòu)函數(shù)調(diào)用" << endl;

}

class Cat :public Animal

{

public:

Cat(string name)

{

cout << "Cat的構(gòu)造函數(shù)調(diào)用" << endl;

m_Name = new string (name);

}

virtual void speak()

{

cout << *m_Name << "小貓在說話" << endl;

}

~Cat()

{

if (m_Name != NULL)

{

cout << "Cat的虛析構(gòu)函數(shù)調(diào)用" << endl;

delete m_Name;

m_Name = NULL;

}

}

string *m_Name;

};

void test01()

{

Animal * animal = new Cat("Tom");

animal->speak();

// 父類指針在析構(gòu)的時候 不會調(diào)用子類中的析構(gòu)函數(shù),導(dǎo)致子類如果有堆區(qū)屬性,出現(xiàn)內(nèi)存泄露

delete animal;

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

Animal的構(gòu)造函數(shù)調(diào)用

Cat的構(gòu)造函數(shù)調(diào)用

Tom小貓在說話

Cat的虛析構(gòu)函數(shù)調(diào)用

Animal的純虛析構(gòu)函數(shù)調(diào)用

Process returned 0 (0x0) execution time : 0.029 s

Press any key to continue.

4.7.4 多態(tài)案例一-計算器類

? 例4.7.4 class calculator

#include

#include

using namespace std;

// 分別利用基本寫法和多態(tài)技術(shù)實現(xiàn)計算器

// 普通寫法

class Calculator

{

public:

int getResult(string oper)

{

if(oper == "+")

{

return m_Num1 + m_Num2;

}

else if(oper == "-")

{

return m_Num1 - m_Num2;

}

else if(oper == "*")

{

return m_Num1 * m_Num2;

}

else if(oper == "/")

{

return m_Num1 / m_Num2;

}

}

int m_Num1;

int m_Num2;

// 如果想拓展新的功能,需要修改源碼

// 在真實開發(fā)中提倡開閉原則

// 開閉原則:對擴(kuò)展進(jìn)行開發(fā),對修改進(jìn)行關(guān)閉

};

void test01()

{

// 創(chuàng)建計算器對象

Calculator c;

c.m_Num1 = 10;

c.m_Num2 = 10;

cout << c.m_Num1 << " + " << c.m_Num2 << " = " << c.getResult("+") << endl;

cout << c.m_Num1 << " - " << c.m_Num2 << " = " << c.getResult("-") << endl;

cout << c.m_Num1 << " * " << c.m_Num2 << " = " << c.getResult("*") << endl;

cout << c.m_Num1 << " / " << c.m_Num2 << " = " << c.getResult("/") << endl;

}

// 利用多態(tài)實現(xiàn)計算器

// 實現(xiàn)計算器抽象類

class AbstractCalculator

{

public:

virtual int getResult()

{

return 0;

}

int m_Num1;

int m_Num2;

};

// 加法計算器類

class Add :public AbstractCalculator

{

virtual int getResult()

{

return m_Num1 + m_Num2;

}

};

// 減法計算器類

class Sub :public AbstractCalculator

{

virtual int getResult()

{

return m_Num1 - m_Num2;

}

};

// 乘法計算器類

class Mul :public AbstractCalculator

{

virtual int getResult()

{

return m_Num1 * m_Num2;

}

};

// 除法計算器類

class Div :public AbstractCalculator

{

virtual int getResult()

{

return m_Num1 / m_Num2;

}

};

void test02()

{

// 多態(tài)使用條件

// 父類指針或者引用指向子類對象

// 加法運算

AbstractCalculator * abc = new Add;

abc->m_Num1 = 20;

abc->m_Num2 = 20;

cout << abc->m_Num1 << " + " << abc->m_Num2 << " = " << abc->getResult() << endl;

delete abc;

// 減法運算

abc = new Sub;

abc->m_Num1 = 20;

abc->m_Num2 = 20;

cout << abc->m_Num1 << " - " << abc->m_Num2 << " = " << abc->getResult() << endl;

delete abc;

// 乘法運算

abc = new Mul;

abc->m_Num1 = 20;

abc->m_Num2 = 20;

cout << abc->m_Num1 << " * " << abc->m_Num2 << " = " << abc->getResult() << endl;

delete abc;

// 除法運算

abc = new Div;

abc->m_Num1 = 20;

abc->m_Num2 = 20;

cout << abc->m_Num1 << " / " << abc->m_Num2 << " = " << abc->getResult() << endl;

delete abc;

}

int main()

{

cout << "test01" << endl;

test01();

cout << endl;

cout << "test02" << endl;

test02();

return 0;

}

? 結(jié)果如下:

test01

10 + 10 = 20

10 - 10 = 0

10 * 10 = 100

10 / 10 = 1

test02

20 + 20 = 40

20 - 20 = 0

20 * 20 = 400

20 / 20 = 1

Process returned 0 (0x0) execution time : 0.028 s

Press any key to continue.

4.7.5 多態(tài)案例二-制作飲品

? 例4.7.5 make drinking

#include

using namespace std;

// make drinking

class BaseDrinking

{

public:

virtual ~BaseDrinking()

{

// 基類析構(gòu)函數(shù)實現(xiàn)

}

// 煮水

virtual void Boil() = 0;

// 沖泡

virtual void Brew() = 0;

// 倒入杯中

virtual void PourInCup() = 0;

// 加入輔料

virtual void AddSomethings() = 0;

// 制作飲品

void MakeDrink()

{

Boil();

Brew();

PourInCup();

AddSomethings();

}

};

// 制作咖啡

class Coffee :public BaseDrinking

{

public:

// 煮水

virtual void Boil()

{

cout << "煮農(nóng)夫山泉" << endl;

}

// 沖泡

virtual void Brew()

{

cout << "沖泡咖啡" << endl;

}

// 倒入杯中

virtual void PourInCup()

{

cout << "倒入咖啡杯中" << endl;

}

// 加入輔料

virtual void AddSomethings()

{

cout << "加入糖和牛奶" << endl;

}

};

// 制作茶

class Tea :public BaseDrinking

{

public:

// 煮水

virtual void Boil()

{

cout << "煮娃哈哈" << endl;

}

// 沖泡

virtual void Brew()

{

cout << "沖泡茶" << endl;

}

// 倒入杯中

virtual void PourInCup()

{

cout << "倒入茶杯中" << endl;

}

// 加入輔料

virtual void AddSomethings()

{

cout << "加入檸檬" << endl;

}

};

// 制作函數(shù)

void doWork(BaseDrinking * base)

{

base->MakeDrink();

delete base; // 釋放

}

void test01()

{

// 制作咖啡

doWork(new Coffee);

cout << "---------------------" << endl;

// 制作茶

doWork(new Tea);

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

煮農(nóng)夫山泉

沖泡咖啡

倒入咖啡杯中

加入糖和牛奶

---------------------

煮娃哈哈

沖泡茶

倒入茶杯中

加入檸檬

Process returned 0 (0x0) execution time : 0.078 s

Press any key to continue.

4.7.6 多態(tài)案例三-電腦組裝

? 例4.7.6 assembly computer

#include

using namespace std;

// 組裝電腦

// 抽象不同的零件類

// 抽象CPU類

class CPU

{

public:

virtual ~CPU()

{

}

// 抽象的計算函數(shù)

virtual void calculate() = 0;

};

// 抽象顯卡類

class VideoCard

{

public:

virtual ~VideoCard()

{

}

// 抽象的顯示函數(shù)

virtual void display() = 0;

};

// 抽象內(nèi)存條類

class Memory

{

public:

virtual ~Memory()

{

}

// 抽象的存儲函數(shù)

virtual void storage() = 0;

};

class Computer

{

public:

Computer(CPU * cpu, VideoCard * vc, Memory *mem)

{

m_cpu = cpu;

m_vc = vc;

m_mem = mem;

}

// 提供工作的函數(shù)

void work()

{

// 讓零件工作起來,調(diào)用接口

m_cpu->calculate();

m_vc->display();

m_mem->storage();

}

// 提供析構(gòu)函數(shù) 釋放3個電腦零件

virtual ~Computer()

{

// 釋放CPU零件

if (m_cpu != NULL)

{

delete m_cpu;

m_cpu = NULL;

}

// 釋放顯卡零件

if (m_vc != NULL)

{

delete m_vc;

m_vc = NULL;

}

// 釋放內(nèi)存條零件

if (m_mem != NULL)

{

delete m_mem;

m_mem = NULL;

}

}

private:

CPU * m_cpu; // CPU的零件指針

VideoCard * m_vc; // 顯卡零件指針

Memory * m_mem; // 內(nèi)存條零件指針

};

// 具體廠商

// intel廠商

class IntelCPU :public CPU

{

public:

virtual void calculate()

{

cout << "Intel的CPU開始計算了" << endl;

}

};

class IntelVideoCard :public VideoCard

{

public:

virtual void display()

{

cout << "Intel的顯卡開始顯示了" << endl;

}

};

class IntelMemory :public Memory

{

public:

virtual void storage()

{

cout << "Intel的內(nèi)存條開始存儲了" << endl;

}

};

// AMD廠商

class AMDCPU :public CPU

{

public:

virtual void calculate()

{

cout << "AMD的CPU開始計算了" << endl;

}

};

class AMDVideoCard :public VideoCard

{

public:

virtual void display()

{

cout << "AMD的顯卡開始顯示了" << endl;

}

};

class AMDMemory :public Memory

{

public:

virtual void storage()

{

cout << "AMD的內(nèi)存條開始存儲了" << endl;

}

};

void test01()

{

// 第一臺電腦零件

CPU * intelcpu = new IntelCPU;

VideoCard * intelCard = new IntelVideoCard;

Memory * intelMem = new IntelMemory;

cout << "第一臺電腦開始工作:" << endl;

// 創(chuàng)建第一臺電腦

Computer * Computer1 = new Computer(intelcpu, intelCard, intelMem);

Computer1->work();

delete Computer1;

cout << "----------------------" << endl;

cout << "第二臺電腦開始工作:" << endl;

// 第二臺電腦組裝

Computer * Computer2 = new Computer(new AMDCPU, new AMDVideoCard, new AMDMemory);

Computer2->work();

delete Computer2;

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

第一臺電腦開始工作:

Intel的CPU開始計算了

Intel的顯卡開始顯示了

Intel的內(nèi)存條開始存儲了

----------------------

第二臺電腦開始工作:

AMD的CPU開始計算了

AMD的顯卡開始顯示了

AMD的內(nèi)存條開始存儲了

Process returned 0 (0x0) execution time : 0.072 s

Press any key to continue.

4.7.7 繼承與多態(tài)案例

? 題目如下:

? 上機(jī)實驗五 繼承與多態(tài),請沿用實驗三的實驗結(jié)果, 以公開(public)繼承 Person 類產(chǎn)生一個 Student 類(class)。 以及 Teacher 類。注意: Person 類的 print()成員已經(jīng)設(shè)為虛函數(shù)(virtual function)。 ? 將類定義(class definition)寫在 Person.h, Date.h, Student.h 及 Teacher.h 中。 將成員函數(shù)的定義(member function definition)寫在person.cpp, Date.cpp, Student.cpp 及Teacher.cpp 中。在主程序中實例化二個 Person對象,二個 Student 對象,一個 Teacher 對象。并在主程序中定義一個 Person 的指針數(shù)組,將數(shù)組中的指針分別指向上述五個對象。 利用 for 及指針數(shù)組調(diào)用數(shù)組指針指向的每個對象的 print 成員函數(shù)順序打印對象的內(nèi)容。 ? Person

-Name : string

-ID : int

-Address : string

-Birthday: Date

<> +Person(name : string = “”, id : int = 0,

address : string = “”, Date = Date())

<> +~Person()

+setName(name : string)

+getName() : string

+setID(id : int)

+getID() : int

+setAddress(address : string)

+getAddress() : string

+setBirthday(d : Date)

+getBirthday() : Date

+virtual print() : void

? Date

<>+Date(y : int = 0,

m : int = 0, d : int = 0)

<>+~Date()

+setYear(y : int) : void

+setMonth(m : int) : void

+setDay(d : int) : void

+getYear() : int

+getMonth() : int

+getDay() : int

+print() : void

-Year : int

-Month : int

-Day : int

Student

-Department:string

-studentID:int

<> +Student (name:string=””,

id:int=0, address:string=””, Date=Date(),

Dep:string=””, sID:int=0)

<> +~Student()

+setDepartment(Dep:string):void

+setStudentID(sID:int):void

+getDepartment():string

+getStudentID():int

+print():void

? Teacher

-Department:string

-Salary:double

<> +Teacher(name:string,

id:int=0, address:string=””, Date=Date(),

Dep:string=””,sal:double=0.0)

<> +~Teacher()

+setDepartment(Dep:string):void

+setSalary(sal:duble):void

+getDepartment():string

+getSalary():double

+print():void

? 解答如下:

? main.cpp

#include

#include "Person.h"

#include "Student.h"

#include "Teacher.h"

using namespace std;

int main()

{

Person p1("Alice", 1, "123 Street");

Person p2("Bob", 2, "456 Avenue");

Student s1("Charlie", 3, "789 Boulevard", Date(2000, 3, 1), "Math", 1001);

Student s2("David", 4, "101 Lane", Date(2001, 7, 22), "Physics", 1002);

Teacher t1("Eve", 5, "202 Road", Date(1975, 1, 1), "Biology", 50000);

Person* people[] = {&p1, &p2, &s1, &s2, &t1}; // 容器

for (const auto& person : people) // output

{

person->print();

}

return 0;

}

? Person.h

#ifndef PERSON_H

#define PERSON_H

#include

#include "Date.h"

using namespace std;

class Person

{

public:

Person();

Person(string name, int id, string address);

~Person();

void setPerson(string name, int id, string address);

void setName(string name);

void setID(int id);

void setAddress(string address);

void setBirthday(Date d);

string getName();

int getID();

string getAddress();

Date getBirthday();

virtual void print(); // outPutResult

private:

string Name;

int ID;

string Address;

Date Birthday;

};

#endif // PERSON_H

? Student.h

#ifndef STUDENT_H

#define STUDENT_H

#include

#include "Person.h"

#include "Date.h"

using namespace std;

class Student :public Person

{

public:

Student();

Student(string name, int id, string address, Date date, string department, int studentID);

~Student();

void setDepartment(string department);

void setStudentID(int studentID);

string getDepartment();

int getStudentID();

virtual void print(); // outPutResult

private:

string Department;

int StudentID;

};

#endif // STUDENT_H

? Teacher.h

#ifndef TEACHER_H

#define TEACHER_H

#include "Person.h"

#include "Date.h"

using namespace std;

class Teacher :public Person

{

public:

Teacher();

Teacher(string name, int id, string address, Date date, string department, double salary);

~Teacher();

void setDepartment(string department);

void setSalary(double salary);

string getDepartment();

double getSalary();

virtual void print(); // outPutResult

private:

string Department;

double Salary;

};

#endif // TEACHER_H

? Person.cpp

#include "Person.h"

#include

using namespace std;

Person::Person()

{

Name = "S.M.Wang";

ID = 070145;

Address = "蓮花路200號";

}

Person::Person(string name, int id, string address)

{

setPerson(name, id, address);

}

Person::~Person()

{

//cout << "object Destructor is called" << endl;

}

void Person::setPerson(string name, int id, string address)

{

Name = name;

ID = id;

Address = address;

}

void Person::setName(string name)

{

Name = name;

}

void Person::setID(int id)

{

ID = id;

}

void Person::setAddress(string address)

{

Address = address;

}

string Person::getName()

{

return Name;

}

int Person::getID()

{

return ID;

}

string Person::getAddress()

{

return Address;

}

void Person::setBirthday(Date d) // 調(diào)用的形參是類

{

Birthday = d;

}

Date Person::getBirthday() // 返回的是類

{

return Birthday;

}

void Person::print()

{

cout << "Name:" << getName() << endl;

cout << "ID:" << getID() << endl;

cout << "Address:" << getAddress() << endl;

cout << "Birthday:" << getBirthday().getYear(); // getBirthday()返回的是類,再調(diào)用類中的子函數(shù)滿足cout的返回值。

cout << " " << getBirthday().getMonth();

cout << " " << getBirthday().getDay() << endl;

cout << endl;

}

? Student.cpp

#include "Student.h"

#include

using namespace std;

Student::Student()

{

}

Student::Student(string name, int id, string address, Date date, string department, int studentID)

{

setPerson(name, id, address);

setBirthday(date);

setDepartment(department);

setStudentID(studentID);

}

Student::~Student()

{

//cout << "object Destructor is called" << endl;

}

void Student::setDepartment(string department)

{

Department = department;

}

string Student::getDepartment()

{

return Department;

}

void Student::setStudentID(int studentID)

{

StudentID = studentID;

}

int Student::getStudentID()

{

return StudentID;

}

void Student::print()

{

cout << "Name:" << getName() << endl;

cout << "ID:" << getID() << endl;

cout << "Address:" << getAddress() << endl;

cout << "Birthday:" << getBirthday().getYear(); // getBirthday()返回的是類,再調(diào)用類中的子函數(shù)滿足cout的返回值。

cout << " " << getBirthday().getMonth();

cout << " " << getBirthday().getDay() << endl;

cout << "Department:" << getDepartment() << endl;

cout << "StudentID:" << getStudentID() << endl;

cout << endl;

}

? Teacher.cpp

#include "Teacher.h"

#include

using namespace std;

Teacher::Teacher()

{

}

Teacher::Teacher(string name, int id, string address, Date date, string department, double salary)

{

setPerson(name, id, address);

setBirthday(date);

setDepartment(department);

setSalary(salary);

}

Teacher::~Teacher()

{

//cout << "object Destructor is called" << endl;

}

void Teacher::setDepartment(string department)

{

Department = department;

}

string Teacher::getDepartment()

{

return Department;

}

void Teacher::setSalary(double salary)

{

Salary = salary;

}

double Teacher::getSalary()

{

return Salary;

}

void Teacher::print()

{

cout << "Name:" << getName() << endl;

cout << "ID:" << getID() << endl;

cout << "Address:" << getAddress() << endl;

cout << "Birthday:" << getBirthday().getYear(); // getBirthday()返回的是類,再調(diào)用類中的子函數(shù)滿足cout的返回值。

cout << " " << getBirthday().getMonth();

cout << " " << getBirthday().getDay() << endl;

cout << "Department:" << getDepartment() << endl;

cout << "Salary:" << getSalary() << endl;

cout << endl;

}

? 結(jié)果如下:

Name:Bob

ID:2

Address:456 Avenue

Birthday:0 0 0

Name:Charlie

ID:3

Address:789 Boulevard

Birthday:2000 3 1

Department:Math

StudentID:1001

Name:David

ID:4

Address:101 Lane

Birthday:2001 7 22

Department:Physics

StudentID:1002

Name:Eve

ID:5

Address:202 Road

Birthday:1975 1 1

Department:Biology

Salary:50000

Process returned 0 (0x0) execution time : 0.011 s

Press any key to continue.

5 文件操作

? 程序運行時產(chǎn)生的數(shù)據(jù)都屬于臨時數(shù)據(jù),程序一旦運行結(jié)束都會被釋放。

通過文件可以將數(shù)據(jù)持久化。

C++中對文件操作需要包含頭文件 < fstream >

? 文件類型分為兩種:

文本文件 - 文件以文本的ASCII碼形式存儲在計算機(jī)中。二進(jìn)制文件 - 文件以文本的二進(jìn)制形式存儲在計算機(jī)中,用戶一般不能直接讀懂它們。

? 操作文件的三大類:

ofstream:寫操作ifstream: 讀操作fstream : 讀寫操作

5.1文本文件

5.1.1寫文件

寫文件步驟如下:

包含頭文件 #include

創(chuàng)建流對象 ofstream ofs;

打開文件 ofs.open("文件路徑",打開方式);

寫數(shù)據(jù) ofs << "寫入的數(shù)據(jù)";

關(guān)閉文件 ofs.close();

? 文件打開方式:

打開方式解釋ios::in為讀文件而打開文件ios::out為寫文件而打開文件ios::ate初始位置:文件尾ios::app追加方式寫文件ios::trunc如果文件存在先刪除,再創(chuàng)建ios::binary二進(jìn)制方式

? 例5.1.1

#include

#include

using namespace std;

void test01()

{

ofstream ofs;

ofs.open("test.txt", ios::out);

ofs << "姓名:張三" << endl;

ofs << "性別:男" << endl;

ofs << "年齡:18" << endl;

ofs.close();

}

int main()

{

test01();

return 0;

}

? test.txt 內(nèi)容如下:

姓名:張三

性別:男

年齡:18

5.1.2讀文件

? 讀文件步驟如下:

包含頭文件 #include

創(chuàng)建流對象 ifstream ifs;

打開文件并判斷文件是否打開成功 ifs.open("文件路徑",打開方式);

讀數(shù)據(jù) 四種方式讀取

關(guān)閉文件 ifs.close();

? 例5.1.2

#include

#include

using namespace std;

void test01()

{

ifstream ifs;

ifs.open("C://Users//TeaInCoffee//Desktop//test.txt", ios::in);

if (!ifs.is_open())

{

cout << "文件打開失敗" << endl;

return;

}

//第一種方式

//char buf[1024] = { 0 };

//while (ifs >> buf)

//{

// cout << buf << endl;

//}

//第二種

//char buf[1024] = { 0 };

//while (ifs.getline(buf,sizeof(buf)))

//{

// cout << buf << endl;

//}

//第三種

//string buf;

//while (getline(ifs, buf))

//{

// cout << buf << endl;

//}

char c;

while ((c = ifs.get()) != EOF)

{

cout << c;

}

ifs.close();

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

姓名:張三

性別:男

年齡:18

Process returned 0 (0x0) execution time : 0.014 s

Press any key to continue.

5.2 二進(jìn)制文件

? 以二進(jìn)制的方式對文件進(jìn)行讀寫操作。

? 打開方式要指定為 ios::binary

5.2.1 寫文件

? 二進(jìn)制方式寫文件主要利用流對象調(diào)用成員函數(shù)write。

? 函數(shù)原型 :

ostream& write(const char * buffer,int len);

? 參數(shù)解釋:字符指針buffer指向內(nèi)存中一段存儲空間,len是讀寫的字節(jié)數(shù)。

? 例5.2.1

#include

#include

using namespace std;

class Person

{

public:

char m_Name[64];

int m_Age;

};

//二進(jìn)制文件 寫文件

void test01()

{

//1、包含頭文件

//2、創(chuàng)建輸出流對象

ofstream ofs("C://Users//TeaInCoffee//Desktop//person.txt", ios::out | ios::binary);

//3、打開文件

//ofs.open("C://Users//TeaInCoffee//Desktop//person.txt", ios::out | ios::binary);

Person p = {"張三" , 18};

//4、寫文件

ofs.write((const char *)&p, sizeof(p));

//5、關(guān)閉文件

ofs.close();

}

int main()

{

test01();

return 0;

}

? person.txt 內(nèi)容如下:

??

5.2.2 讀文件

? 二進(jìn)制方式讀文件主要利用流對象調(diào)用成員函數(shù)read。

? 函數(shù)原型:

istream& read(char *buffer,int len);

? 參數(shù)解釋:字符指針buffer指向內(nèi)存中一段存儲空間。len是讀寫的字節(jié)數(shù)。

? 例5.2.2

#include

#include

using namespace std;

class Person

{

public:

char m_Name[64];

int m_Age;

};

void test01()

{

ifstream ifs("C://Users//TeaInCoffee//Desktop//person.txt", ios::in | ios::binary);

if (!ifs.is_open())

{

cout << "文件打開失敗" << endl;

}

Person p;

ifs.read((char *)&p, sizeof(p));

cout << "姓名: " << p.m_Name << " 年齡: " << p.m_Age << endl;

}

int main()

{

test01();

return 0;

}

? 結(jié)果如下:

姓名: 張三 年齡: 18

Process returned 0 (0x0) execution time : 0.011 s

Press any key to continue.

柚子快報激活碼778899分享:C++詳解

http://yzkb.51969.com/

相關(guān)鏈接

評論可見,查看隱藏內(nèi)容

本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點和立場。

轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。

本文鏈接:http://gantiao.com.cn/post/19579428.html

發(fā)布評論

您暫未設(shè)置收款碼

請在主題配置——文章設(shè)置里上傳

掃描二維碼手機(jī)訪問

文章目錄