数据抽象
数据抽象是一种依赖于接口和实现分离的编程(设计)技术
数据抽象有两个重要的优势:
1.类的内部受到保护,不会因无意的用户级错误导致对象状态受损。
2.类实现可能随着时间的推移而发生变化,以便应对不断变化的需求,或者应对那些要求不改变用户级代码的错误报告。
#include <iostream>
using namespace std;
class Adder{
public:
Adder(int i = 0) {// 构造函数
total = i;
}
void addNum(int number) {// 对外的接口
total += number;
}
int getTotal() {// 对外的接口
return total;
};
private:
int total; // 对外隐藏的数据
}
int main() {
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
cout << "Total " << a.getTotal() <<endl; return 0;
}
//结果Total 60
上面的类把数字相加,并返回总和。公有成员 addNum 和 getTotal 是对外的接口,用户需要知道它们以便使用类。私有成员 total 是用户不需要了解的,但又是类能正常工作所必需的。
数据封装
封装是面向对象编程中的把数据和操作数据的函数绑定在一起的一个概念,这样能避免受到外界的干扰和误用,从而确保了安全。数据封装引申出了另一个重要的 OOP 概念,即数据隐藏。
#include <iostream>
using namespace std;
class Adder{
public: // 构造函数
Adder(int i = 0) {
total = i;
} // 对外的接口
void addNum(int number) {
total += number;
} // 对外的接口
int getTotal() {
return total;
}
private: // 对外隐藏的数据
int total;
};
int main( ) {
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
cout << "Total " << a.getTotal() <<endl;
return 0;
}
抽象类
抽象类是一种特殊的类,它是为了抽象和设计的目的为建立的,它处于继承层次结构的较上层。
(1)抽象类的定义:至少有一个函数被声明为纯虚函数,则这个类就是抽象类。
class Box {
public:
virtual double getVolume() = 0;// 纯虚函数
private:
double length; // 长度
double breadth; // 宽度
double height; // 高度
};