在班上隐藏私人会员的最佳方法
Best way to hide private members in a class
我在标头文件中具有以下代码
class Bar {
public:
void public_foo();
private:
void private_foo();
};
该实现隐藏在源文件中
void Bar::public_foo(){
private_foo();
}
void Bar::private_foo(){
// Some more stuff
}
我希望在标题文件中看到私有功能。做这个的最好方式是什么?我知道两种方法:
1(使private_foo
像这样的非会员函数
void private_foo(Bar* this){ /* ... */ }
并将其称为public_foo
:private_foo(this)
。这对我来说不是很吸引人,因为它不是特别的编程。
2(使用隐藏的实现类
// In header
class Bar {
public:
virtual void public_foo();
virtual ~Bar() { };
};
Bar* CreateBar();
// In Source
class Bar_impl : public Bar {
public:
void public_foo();
private:
void private_foo();
};
Bar* CreateBar(){
return new Bar_impl;
}
void Bar::public_foo(){
private_foo();
}
void Bar::private_foo(){
// Some more stuff
}
这有效,但是对于如此简单的东西来说,这太多了。
是否有第三种(更好的(方法?
编辑:响应@jdehesa,并且由于我喜欢戴上语言设计师的帽子,这是我理想的语法(不正确的C 语法,但可以做梦(
// In header
class Bar {
public:
void public_foo();
};
// In Source
classdef Bar { // Notice my new "classdef" keyword
public:
void public_foo(){
}
private:
void private_foo(){
}
};
一个问题是,对于正确的内存分配,实现类无法添加额外的变量(公共或私有变量(。
您可以使用pimpl成语
示例:
// Pimpl idiom - basic idea
class widget {
// :::
private:
struct impl; // things to be hidden go here
impl* pimpl_; // opaque pointer to forward-declared class
};
相关文章:
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 在C++中向零方向近似的最佳方法
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 检测win32服务创建和删除的最佳方法
- 在C++中样板"冷/never_inline"错误处理技术的最佳方法是什么?
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 将线程中的数据存储到全局容器的最佳方法?
- 将一系列整数放入类的最佳方法是什么?
- 在派生类中使用基类的私有成员变量的最佳方法
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- Qt - QVector 和模型视图 - 从列表视图获取自定义类的最佳方法是什么?
- 使用 Git 处理 C++ Visual Studio 2019 解决方案的外部依赖项源代码管理的最佳方法是什么?
- 比较两个节点坐标的最佳方法是什么?
- 在nodejs中使用本机代码的最佳方法是什么?
- 将 pybind11 绑定标记为已弃用的最佳方法
- C++:将向量传递到构造函数以创建成员变量的最佳方法?
- C++中变量混叠的最佳方法
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?