c++基础学习(09)--(数据抽象、数据封装、接口)
生活随笔
收集整理的這篇文章主要介紹了
c++基础学习(09)--(数据抽象、数据封装、接口)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
文章目錄
- 目錄
- 1.數(shù)據(jù)抽象
- 2.數(shù)據(jù)封裝
- 3.抽象接口類
目錄
1.數(shù)據(jù)抽象
數(shù)據(jù)抽象:就是把它當(dāng)做黑箱子使用,內(nèi)部實現(xiàn)與外部接口分開
C++類實現(xiàn)數(shù)據(jù)抽象,如sort()函數(shù),ostream的cout對象
當(dāng)上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:
Total 60
2.數(shù)據(jù)封裝
#include <iostream> using namespace std;class Adder{public:// 構(gòu)造函數(shù)Adder(int i = 0){total = i;}// 對外的接口void addNum(int number){total += number;}// 對外的接口int getTotal(){return total;};private:// 對外隱藏的數(shù)據(jù)int total; }; int main( ) {Adder a;a.addNum(10);a.addNum(20);a.addNum(30);cout << "Total " << a.getTotal() <<endl;return 0; }當(dāng)上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:
Total 60
3.抽象接口類
#include <iostream>using namespace std;// 基類 class Shape { public:// 提供接口框架的純虛函數(shù)virtual int getArea() = 0;void setWidth(int w){width = w;}void setHeight(int h){height = h;} protected:int width;int height; };// 派生類 class Rectangle: public Shape { public:int getArea(){ return (width * height); } }; class Triangle: public Shape { public:int getArea(){ return (width * height)/2; } };int main(void) {Rectangle Rect;Triangle Tri;Rect.setWidth(5);Rect.setHeight(7);// 輸出對象的面積cout << "Total Rectangle area: " << Rect.getArea() << endl;Tri.setWidth(5);Tri.setHeight(7);// 輸出對象的面積cout << "Total Triangle area: " << Tri.getArea() << endl; return 0; }當(dāng)上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:
Total Rectangle area: 35
Total Triangle area: 17
總結(jié)
以上是生活随笔為你收集整理的c++基础学习(09)--(数据抽象、数据封装、接口)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: DeepLearning.ai 提炼笔记
- 下一篇: 数据结构和算法(06)---二叉树(c+