C++ 编程深入解析:从封装到标准库的全面探究
1. 封装机制及其突破
封装是面向对象编程中的重要概念,它将数据隐藏在类的私有部分,仅允许通过类的方法来访问这些数据。然而,在 C++ 中,这种封装仅在编译阶段提供保护。
以下是一个简单的示例代码:
#include <stdio.h>
class box
{
private:
int color, width, height, depth;
public:
box(int color, int width, int height, int depth)
{
this->color = color;
this->width = width;
this->height = height;
this->depth = depth;
};
void dump()
{
printf("this is box. color=%d, width=%d, height=%d, depth=%d\n", color, width, height, depth);
};
};
这个类 box 包含了四个私有成员变量,并且提供了构造函数和 dump 方法。
如果我们尝试直接访问私有成员,编译器会报错:
void hack_oop_enca
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



