C++ 抽象

来源:这里教程网 时间:2026-02-16 16:05:02 作者:

抽象是面向对象编程的功能之一,您只需向用户显示相关详细信息并隐藏不相关的详细信息。例如,当您向某人发送电子邮件时,您只需单击“发送”即可获得成功消息,单击“发送”时实际发生的情况,数据通过网络传输给收件人的方式对您来说是隐藏的(因为它与您无关) 。

让我们看看如何使用访问说明符在 C++ 程序中实现:

抽象示例

#include <iostream>using namespace std;class AbstractionExample{private:   /* By making these data members private, I have    * hidden them from outside world.    * These data members are not accessible outside    * the class. The only way to set and get their    * values is through the public functions.    */   int num;   char ch;public:   void setMyValues(int n, char c) {      num = n; ch = c;   }   void getMyValues() {      cout<<"Numbers is: "<<num<< endl;      cout<<"Char is: "<<ch<<endl;   }};int main(){   AbstractionExample obj;   obj.setMyValues(100, 'X');   obj.getMyValues();   return 0;}

输出:

Numbers is: 100Char is: X

数据抽象的优势

使用此功能的主要优点是,当代码发展并且您需要在代码中进行一些调整时,您只需要修改已将成员声明为私有的高级类。由于没有类直接访问这些数据成员,因此您无需更改低级别(用户级别)类代码。

想象一下,如果您将这些数据成员公开,如果在某些时候您想要更改代码,则必须对直接访问成员的所有类进行必要的调整。

数据抽象的其他优点是:

1)通过使数据私有化并避免可能破坏数据的用户级错误,使应用安全。

2)这避免了代码重复并增加了代码的可重用性。

相关推荐