在其中定义仅用作私有成员变量的结构
Where to define struct only to be used as private member variable?
以下面的头文件为例,其中Bar是一个结构体:
class Foo
{
...
private:
Bar _bar;
};
我只希望Bar
可以作为Foo
的私有成员变量访问。什么是正确的方式来声明和定义Bar
?
选项1:define in header?
我想避免这种情况,因为我不希望Bar
在Foo
类范围之外可用。
struct Bar
{
int a;
int b;
...
};
class Foo
{
...
private:
Bar _bar;
};
选项2:在header中向前声明,在cpp中定义?
不确定这是否合法,因为如果Bar
的定义不能直接使用,编译器如何严格从头中知道Foo
的大小?此外,这将隐藏Bar
从其他文件,包括头吗?
struct Bar;
class Foo
{
...
private:
Bar _bar;
};
实现文件:struct Bar
{
int a;
int b;
...
};
选项3:在类
中声明可能是限制作用域的最佳选择,但可能会造成混乱的?
class Foo
{
...
private:
struct Bar
{
int a;
int b;
...
};
Bar _bar;
};
对于要编译的选项2,_bar
应该是指针。选项3是最好的,因为它不会污染命名空间。
选项3:在类
中声明也许限制作用域的最佳选择
当然,这是限制作用域且不污染名称空间的最佳方法。选择选项3
但可能很乱?
我没有得到你的关注(你可能想在你的问题中详细说明),这根本没有什么混乱的。
注意:当需要与客户端进行往返时,他们可以使用auto
关键字来引用Bar
变量。
R.Sahu提到的另一个选择是使用Pimpl习语:
struct FooData;
class Foo {
...
private:
std::unique_ptr<FooData> data_; // Note I not prefer to use leading underscores
public:
Foo();
};
在Foo
的翻译单元中:
namespace {
struct FooData;
{
int a;
int b;
...
};
}
Foo::Foo() : data_(std::make_unique<FooData<()) {}
选项1:define in header?
我希望避免这种情况,因为我不希望Bar在Foo类作用域之外可用。
选项一,你只回答了你自己的问题。
选项2:在header中前向声明,在cpp
中定义
与选项1(作用域可见性)相同的问题,但唯一的优点是Bar的实现对其他.cpp
文件不可见。
选项3:在类
中声明
选项3是最好的,因为它满足了您所要求的目的,而且只有这个目的。此外,Bar
是提供给整个类。此外,嵌套类可以防止代码中不必要的混乱,因为除了Foo
之外没有任何东西可以访问Bar
。而且它绝对不会看起来很乱,而且,你可以像这样声明结构体:
class Foo
{
private:
struct Bar {int a, int b};
//.....
};
对于一个小类,这似乎是可以的,因为它是一个1-liner。缺点是不能向前声明类,如以下答案所示:https://stackoverflow.com/a/951245/6525260.
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 将包含C样式数组的对象初始化为成员变量(C++)
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 在循环中按顺序遍历成员变量
- c++类声明时,相同的例程,不同的成员变量类型
- 如何从另一个文件继承私有成员变量和公共函数
- 在C++类中,是否必须初始化作为数组的成员变量
- 如何从子成员函数修改父公共成员变量
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 从私有成员变量的成员方法返回unique_ptr
- 在派生类中使用基类的私有成员变量的最佳方法
- 静态 constexpr 类成员变量对多线程读取是否安全?
- C++:是否可以使用非静态成员变量模板?
- 打印所有继承的类成员变量和方法
- 如何在复杂继承中访问静态成员变量
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 成员变量与函数概念检查