C++Primer中文版(第四版)题解整理(19)
时间:2025-04-20
时间:2025-04-20
C++Primer题解
习题2.29
区分类中的public部分和private部分。
【解答】
类中public部分定义的成员在程序的任何部分都可以访问。通常在public部分放置操作,以便程序中的其他部分可以执行这些操作。
类中private部分定义的成员只能被作为类的组成部分的代码(以及该类的友元)访问。通常在private部分放置数据,以对对象的内部数据进行隐藏。习题2.30
定义表示下列类型的类的数据成员:
(a)电话号码(b)地址
(c)员工或公司(d)某大学的学生
【解答】
(a)电话号码
classTel_number{
public:
//...对象上的操作
private:
std::stringcountry_number;
std::stringcity_number;
std::stringphone_number;
};
(b)地址
classAddress{
public:
//...对象上的操作
private:
std::stringcountry;
std::stringcity;
std::stringstreet;
std::stringnumber;
};
(c)员工或公司
classEmployee{
public:
//...对象上的操作
private:
std::stringID;
std::stringname;
charsex;