
数据抽象
数据抽象(data abstraction)是与面向对象(object-oriented)并列的一种编程范式(programming paradigm)。数据抽象也成为抽象数据类型(abstract data type/ADT)。
数据抽象是一种依赖于接口和实现分离的编程(设计)技术。
https://wizardforcel.gitbooks.io/sicp-py/content/2.2.html
http://wj196.iteye.com/blog/860303
https://blog.csdn.net/Solstice/article/details/6707148
C++类为数据抽象提供了可能。它们向外界提供了大量用于操作对象数据的公共方法,也就是说,外界实际上并不清楚类的内部实现。
数据抽象仅为用户暴露接口,而把具体的实现隐藏了起来
数据抽象的两个优势
- 类的内部受到保护,不会因为无意的用户级错误导致对象状态受损。
 
- 类实现可能随着时间的推移而发生变化,以便应对不断变化的需求,或者应对哪些不改变用户级代码的错误报告。
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
   | 
  #include<iostream> using namespace std;
  class Student { 	private: 		 	    int num; 		int score; 	public: 		 	    Student() 		{ 			cout<<"Constructor called !"<<endl; 		} 		 		int SetNum(int number) 		{ 			this->num = number; 		    return num; 		} 		 		int SetScore(int s) 		{ 			this->score = s; 			return score; 		} };
  int main() { 	Student A; 	cout<<A.SetScore(20)<<endl; 	cout<<A.SetNum(17001)<<endl; 	return 0; }
 
  | 
 

数据封装
数据封装是一种把数据和操作数据的函数捆绑在一起的机制。
C++程序中,任何带有公有和私有成员的类都可以作为数据封装和数据抽象的实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
   | #include<iostream> using namespace std;
  class Adder { 	private: 		 		int total; 	public: 	    Adder(int i=0) 		{ 			total = i; 		} 		 		void addNum(int number) 		{ 			total += number; 		} 		 		int getTotal() 		{ 			return total; 		} };
  int main() {     Adder A;     A.addNum(10);     A.addNum(33);
      cout<<"Total: "<<A.getTotal()<<endl;     return 0; }
 
 
 
 
   | 
 
接口(抽象类)
如果类中至少有一个函数被声明为纯虚函数,则这个类就是抽象类。
抽象类是一种只能定义,不能生成对象的类。
- 抽象类不能用于实例化对象,只能作为接口使用
 
- 如果一个抽象类的子类需要被实例化,则必须实现每个虚函数。即必须在派生类中重载虚函数
 
- 接口描述了类的行为和功能,而不需要完成类的特定实现
 
- 用于实例化对象的类被称为具体类
 
- 抽象类的派类依然可以不完善基类中的纯虚函数,继续作为抽象类被派生,知道给出所有的纯虚函数定义,则成为一个具体类,才可以实例化对象
 
- 抽象类因为抽象、无法具化,所以不能作为参数类型、返回值、强转类型
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
   | //example: #include<iostream> using namespace std;
  class Shape{                //基类 	protected: 		int width; 		int height; 	public: 		//提供接口框架的纯虚函数 		virtual int getArea() = 0;
  		void setWidth(int w) 		{ 			this->width = w; 		} 		void setHeight(int h) 		{ 			this->height = h; 		} };
  //派生类 class Rectangle:public Shape{ 	public: 		int getArea() 		{ 			return width*height; 		} };
  class Triangle:public Shape{ 	public: 		int getArea() 		{ 			return (width*height)/2; 		} };
  int main() { 	Rectangle A;  //矩形 	Triangle B;   //三角形
  	A.setHeight(3); 	A.setWidth(4);
  	B.setHeight(3); 	B.setWidth(4);
  	cout<<"Total Rectangle area: "<<A.getArea()<<endl; 	cout<<"Total Triangle area: "<<B.getArea()<<endl;
  	return 0; }
   | 
 

total
- 数据抽象是一种仅向用户暴露接口而把具体实现细节隐藏起来的一种机制
 
- 数据封装是一种把数据和操作数据的函数捆绑在一起的机制
 
- 抽象类作为接口使用,不能用于实例化对象