为了账号安全,请及时绑定邮箱和手机立即绑定
课程 \ C++远征之封装篇(上)

C++远征之封装篇(上)

4-3 单元巩固
#include <iostream>
#include <string>
using namespace std;

/**
* 定义类:Student
* 数据成员:m_strName
* 数据成员的封装函数:setName()、getName()
*/
class Student
{
public:
// 定义数据成员封装函数setName()
void setName(string name){
m_strName = name;
}


// 定义数据成员封装函数getName()
string getName(){
return m_strName;
}


//定义Student类私有数据成员m_strName
private:
string m_strName;

};

int main()
{
// 使用new关键字,实例化对象
Student *str = new Student();
// 设置对象的数据成员
str->setName("慕课网");
// 使用cout打印对象str的数据成员
cout << str->getName() << endl;
// 将对象str的内存释放,并将其置空
delete str;
str = NULL;
return 0;
}
2020-05-04 查看完整代码
3-2 单元巩固
#include <iostream>
#include <string>
using namespace std;

/**
* 定义类:Student
* 数据成员:名字、年龄
*/
class Student
{
public:
// 定义数据成员名字 m_strName 和年龄 m_iAge
string m_strName;
int m_iAge;
};

int main()
{
// 实例化一个Student对象stu
Student stu;
// 设置对象的数据成员
stu.m_strName = "慕课网";
stu.m_iAge = 2;

// 通过cout打印stu对象的数据成员
cout << stu.m_strName << " " << stu.m_iAge<< endl;
return 0;
}
2020-04-19 查看完整代码
意见反馈 帮助中心 APP下载
官方微信