类的嵌套 、封装
2.2.6 类的嵌套
C++⽀持在⼀个类内部定义另⼀个类(内部类),内部类的作⽤域仅限于外部类。 基本语法:
定义:
访问:
代码⽰例:
//在本程序中的其他⽂件中也⽆法使用该fun函数,也就是把fun函数的作用域限制在本⽂件范
围中。
namespace // 声明一个⽆名的命名空间
{
int count=100;
string name="pk";
}
int main()
{
cout << count << name << endl;
return 0;
}
#include <iostream>
// 方式1:直接指定
std::cout << "Hello" << std::endl;
// 方式2:使用using声明
using namespace std;
cout << "Hello" << endl; // 可直接使用std内的标识符
class 外部类
{
权限访问修饰符:
class 内部类
{
// ..
}
};
外部类::内部类 内部类对象;
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Outer // 外部类
{
private:// 私有权限:只能在当前类内部不访问
int outerData; // 私有的成员变量,只能在当前类内部访问
public: // 公有权限:类的内部以及类的外部都可访问
class Inner // 内部类
{
private:
int innerData;
public:
void setData(int d)
{
类的嵌套相当于给内部类设置了⼀层作⽤域。
说明:
内部类如果是公有访问属性,在外部类的类外,可以通过 外部类::内部类 访问到内部
类;
内部类如果是私有/保护访问属性,在外部类的类外,想访问到内部类,只能通过外部类内
提供内部类的公有对象做数据成员来实现。 封装
2.3.1 封装的意义
封装是将对象的属性和⽅法捆绑在⼀起,隐藏内部实现细节,仅通过公有接⼝与外部交互。其核⼼
意义在于:
保护数据安全性,防⽌不合理的修改
简化外部使⽤,只需关注接⼝⽽⽆需了解内部实现
int main(int argc, char **argv)
{
Outer::Inner in;
in.setData(10);
return 0;
}
公共权限
public
√
√
保护权限
protected
√
×
私有权限
private
√
×
2.3.1.2 访问权限修饰符
类的设计需要使⽤到权限访问修饰符:
上⾯清晰展⽰了三种权限在类内部和类外部的访问规则,其中:
public 权限的成员在类内部和类外部都可以直接访问
protected 和 private 权限的成员仅能在类内部访问,类外⽆法直接访问( protected 和
private 的区别主要是在继承场景中)。
2.3.2 封装⽰例
⽰例1:学⽣类
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
// 创建一个学生类
class Student
{
private: // 私有权限,仅能在类内访问
⽰例2:圆类
string m_name; // 姓名
int m_id; // 学号
public: // 公有权限,类内部和类外部均可访问
// 设置姓名
void setName(string name) {m_name = name;}
// 设置学号
void setId(int id) {m_id = id;}
// 显示学生信息
void showInfo()
{
cout << "学号:" << m_id << ",姓名:" << m_name << endl;
}
};
int main(int argc, char **argv)
{
Student stu;
stu.setId(1001);
stu.setName("张三");
stu.showInfo(); // 学号:1001,姓名:张三
return 0;
}
#include <iostream>
using namespace std;
const double PI = 3.14159; // 全局常量
class Circle {
private:
double m_radius; // 半径
public:
// 设置半径
void setRadius(double r) {
m_radius = r;
}
// 计算周长
double calculateCircumference() {
2.3.3 struct和class的区别
在C++中struct和class的唯⼀的区别就在于默认的访问权限不同。
区别:
struct 默认权限为公有
class 默认权限为私有
代码⽰例:
return 2 * PI * m_radius;
}
};
int main() {
Circle c1;
c1.setRadius(5);
cout << "圆的周长:" << c1.calculateCircumference() << endl; // 约31.4159
return 0;
}
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
// 类
class C1
{
int m_A; // 不加访问权限,默认私有
};
// 结构体
2.3.4 课堂练习
练习1:设计⽴⽅体类
设计⽴⽅体类(Cube)
求出⽴⽅体的⾯积和体积
分别⽤全局函数和成员函数判断两个⽴⽅体是否相等。
struct C2
{
int m_A; // 不加访问权限,默认公有
};
int main(int argc, char **argv)
{
C1 c1;
// c1.m_A = 10; // 错误:访问权限为私有
C2 c2; // C++中,访问结构体的时候,可以省略struct关键字
c2.m_A = 10; // 正确:访
cout << c2.m_A << endl;
return 0;
}
