注:转载请标明原文出处链接: https://lvxiaowen.blog.youkuaiyun.com/article/details/107237750
1 面向对象的思想
上图的写法违背了面向对象的基本思想。
面向对象核心思想:以对象为中心,即以“谁做什么”来表达程序的逻辑。体现到代码层面:将所有的数据操作转化为成员函数的调用,即对象在程序中的所有行为都通过调用自己的函数来完成,如下图所示:
2 封装的好处
如上图所示,年龄一般不可能超过1000。在输入的时候,需要有一个逻辑判断,对传入的参数进行的条件限定,如下图所示:
封装可以对传入的参数起到条件限定的作用。
3 示例
题目描述:
定义一个Student类,包含姓名、性别、学分(只读)、学习,使用get和set函数封装数据成员。在main函数中分别通过栈和堆实例化对象,并打印其相关函数。
#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;
class Student
{
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;
}
void initScore()
{
m_iScore = 0;
}
void study(int _score)
{
m_iScore += _score;
}
int getScore()
{
return m_iScore;
}
private:
string m_strName;
string m_strGender;
int m_iScore;
};
int main()
{
cout << "姓名" << " " << "年龄" << " " << "总成绩" << endl;
//从栈上实例化对象
Student stu1;
stu1.initScore();
stu1.setName("张三");
stu1.setGender("男");
stu1.study(80);
stu1.study(90);
cout << stu1.getName() << " " << stu1.getGender() << " " << stu1.getScore() << endl;
//从堆上实例化对象
Student *stu2 = new Student();
if (NULL == stu2)
return 0;
stu2->initScore();
stu2->setName("李四");
stu2->setGender("女");
stu2->study(90);
stu2->study(100);
cout << stu2->getName() << " " << stu2->getGender() << " " << stu2->getScore() << endl;
delete stu2;
stu2 = NULL;
system("pause");
return 0;
}
运行结果: