使用数据隐藏和封装来存储学生信息的C++程序


假设我们想要创建一个包含数据隐藏和封装的学生数据类型。学生必须具有first_name、last_name、age和class项,但这些变量不能直接访问。我们将不得不定义一些函数,例如get_firstname()、set_firstname()、get_age()、set_age()等来检索和更新变量值,以及一个to_string()函数以以下格式显示学生详细信息(年龄、名字、姓氏、班级)。从控制台获取四个参数作为输入,并使用我们定义的setter方法设置它们,并使用getter方法显示每个项目,最后使用to_string()方法。

因此,如果输入类似于

priyam
kundu
16
10

那么输出将是

16
priyam
kundu
10

(16, priyam, kundu, 10)

为了解决这个问题,我们将遵循以下步骤:

  • 定义一个类,其中first_name、last_name为字符串类型,age、cl为整数类型。

  • 为所有属性定义getter函数。

  • 为所有属性定义setter函数。

  • 使用字符串流对象定义to_string()函数,并创建与输出格式匹配的格式化字符串。

  • 从main方法执行以下操作:

  • 读取每一行,并分别存储first_name、last_name、age、cl。

  • 调用setter函数将这些值设置为类成员。

  • 使用getter方法打印所有属性。

  • 使用to_string()函数以这种格式(年龄、名字、姓氏、cl)显示学生信息。

示例

让我们看看下面的实现,以便更好地理解:

Open Compiler
#include <iostream> #include <sstream> using namespace std; class Student{ private: int age, cl; string first_name, last_name; public: int get_age(){return age;} int get_class(){return cl;} string get_firstname(){return first_name;} string get_lastname(){return last_name;} void set_age(int a){age = a;} void set_class(int c){cl = c;} void set_firstname(string fn){first_name = fn;} void set_lastname(string ln){last_name = ln;} string to_string(){ stringstream ss; ss << "(" << age << ", " << first_name << ", " << last_name << ", " << cl << ")"; return ss.str(); } }; int main() { Student stud; int age, cl; string first_name, last_name; cin >> first_name >> last_name >> age >> cl; stud.set_age(age); stud.set_class(cl); stud.set_firstname(first_name); stud.set_lastname(last_name); cout << stud.get_age() << endl; cout << stud.get_firstname() << endl; cout << stud.get_lastname() << endl; cout << stud.get_class() << endl; cout << endl << stud.to_string(); }

输入

priyam
kundu
16
10

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

16
priyam
kundu
10

(16, priyam, kundu, 10)

更新于: 2021年10月7日

471 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告