4 类和对象
4.1 封装
4.1.1 封装的意义
#include<iostream>
using namespace std;
const double pi = 3.14;
//封装
class Cercle
{
public:
int m_r; //属性
double zhouchang() //行为
{
return 2 * pi * m_r;
}
};
int main()
{
Cercle c1;
c1.m_r = 10;
cout << "圆的周长为:" << c1.zhouchang() << endl;
}
一开始编译未通过:
cout << "圆的周长为:" <<zhouchang() << endl; //未说明是谁的zhouchang()
改为:
cout << "圆的周长为:" << c1.zhouchang() << endl;
示例2:设计一个学生类,可以显示其姓名和学号
我的答案:
#include<iostream>
using namespace std;
class student
{
public:
string m_name;
int m_number;
string name()
{
return m_name;
}
int number()
{
return m_number;
}
};
int main()
{
student s1;
s1.m_name = "张三";
s1.m_number =46;
cout << "学生姓名为:" << s1.name() << "学生学号为:" << s1.number() << endl;
}
老师答案:
#include<iostream>
#include<string>
using namespace std;
class student
{
public:
string m_name;
int m_id;
void setname(string name)
{
m_name=name;
}
void setid(int id)
{
m_id=id;
}
void getxinxi()
{
cout<<"姓名为:"<<m_name<<"\t"<<"学号为:"<<m_id<<endl;
}
};
int main()
{
student s1;
s1.setname("张三");
s1.setid(18);
s1.getxinxi();