MENU

数据的封装,认识面向对象编程

• October 22, 2020 • Read: 2927 • 学习笔记,C++

数据的封装展开目录

需要实现的功能:存储最基本的学生信息。
涉及内容:类,定义成员函数,调用成员函数,保护成员
如,此实例中的:

  • string m_strName;
  • string m_strGender;
  • int m_iScore;

这三个成员即为受保护的三个私有数据成员。

源代码展开目录

源代码中类的数据成员,成员函数都进行了注释,方便理解。

  • #include <iostream>
  • #include <string>
  • using namespace std;
  • /**********************************************/
  • /* 数据的封装
  • 1.姓名 name
  • 2.性别 gender
  • 3.学分(只读) score
  • 4.学习情况 study */
  • /**********************************************/
  • class students
  • {
  • public://公共访问
  • void setName(string _Name)//成员函数
  • {
  • m_strName = _Name;
  • }
  • string getName()//成员函数
  • {
  • return m_strName;
  • }
  • void setGender(string _Gender)//成员函数
  • {
  • m_strGender = _Gender;
  • }
  • string getGender()//成员函数
  • {
  • return m_strGender;
  • }
  • int getScore()//成员函数
  • {
  • return m_iScore;
  • }
  • void iniScore()//成员函数
  • {
  • m_iScore = 0;
  • }
  • void study(int _Score)//成员函数
  • {
  • m_iScore += _Score;
  • }
  • private://私有保护
  • string m_strName;//数据成员
  • string m_strGender;
  • int m_iScore;
  • };
  • int main()
  • {
  • string name, gender;
  • students stu;
  • stu.iniScore();
  • int score;
  • cout << "welcome to students score manage system." << endl
  • << "input student information:" << endl
  • << "name:";
  • cin >> name;
  • stu.setName(name);
  • cout << endl
  • << "gender:";
  • cin >> gender;
  • stu.setGender(gender);
  • cout << endl
  • << "score(if score is 0,input '0' to break increase score,please.):";
  • cin >> score;
  • stu.study(score);
  • while (score != 0)
  • {
  • cout << "iuput next score:";
  • cin >> score;
  • stu.study(score);
  • }
  • cout << endl
  • << "/******************"
  • << "Students Database"
  • << "******************/" << endl;
  • cout << "[student name:" << stu.getName() << "] [student gender:" << stu.getGender() << "] [student score:" << stu.getScore() << "]" << endl;
  • cout << "/******************"
  • << "Students Database"
  • << "******************/" << endl;
  • return 0;
  • }

我们在之前的 C 语言中,通常用结构体 struct 来实现这类需求,那么在 C++ 中我们将认识新的方法 - 类 class 来实现。
类 class 构成了实现 C++ 面向对象编程的基础,在类的说明中,要么是数据成员,要么是成员函数,他们要么说明为 public,要么为 protected,要么为 private。
类具有封装性,这也解释了为什么此文的标题为数据的封装,当类的成员声明为 private 的时候,外部不能对其访问,如以上源代码 students 类中的 m_strName,m_strGender 和 m_iScore,当声明为 public 的时候,则在任何地方都可以访问。

三种访问权限展开目录

public: 可以被任意实体访问
protected: 只允许子类及本类的成员函数访问
private: 只允许本类的成员函数访问

通过本源代码我们认识了什么是类,什么是成员函数,什么又是数据成员,这将使我们踏入面向对象编程的学习之路。

此源代码在线调试地址:点击进入 [ext]


编辑:Henry 2020-10-02

版权属于:字节星球 / 肥柴之家 (转载请联系作者授权)
原文链接:https://www.bytecho.net/archives/cpp1.html
本作品采用知识共享署名 - 非商业性使用 - 相同方式共享 4.0 国际许可协议进行许可。

Last Modified: January 16, 2021
Archives QR Code
QR Code for this page
Tipping QR Code
Leave a Comment

已有 1 条评论
  1. 卿歌 卿歌     macOS    Google Chrome

    爷爷关注的站长有更新了,还是连续的 ::xhl:jingya::