可以通过两种方式实现数据抽象:
使用类进行抽象 - 可以使用类来实现抽象。一个类用于通过使用访问说明符将所有数据成员和成员函数分组为一个单元。类负责确定哪个数据成员在外部是可见的,哪些不是。
头文件中的抽象 - 另一种抽象类型是头文件(header files)。例如,可用的pow()函数用于计算数字的幂而不实际知道哪个算法函数用于计算幂。因此,我们可以说头文件对用户隐藏了所有实现细节。
让我们来看一个简单的头文件抽象示例。
//用于计算数字幂的程序。
#include <iostream> #include<math.h> using namespace std; int main() { int n = 4; int power = 3; int result = pow(n,power); //pow(n,power) 是幂函数 std::cout << "Cube of n is : " <<result<< std::endl; return 0; }
输出:
Cube of n is : 64
在上面的示例中,pow()函数用于计算4的幂3。pow()函数存在于math.h头文件中,其中pow()函数的所有实现细节都被隐藏了。
让我们看一个使用类进行数据抽象的简单示例。
#include <iostream> using namespace std; class Sum { private: int x, y, z;//私有变量 public: void add() { cout<<"Enter two numbers: "; cin>>x>>y; z= x+y; cout<<"Sum of two number is: "<<z<<endl; } }; int main() { Sum sm; sm.add(); return 0; }
输出:
Enter two numbers: 3 6 Sum of two number is: 9
在上面的示例中,使用类实现了抽象。类" Sum"包含私有成员x,y和z只能由该类的成员函数访问。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)