在其中定义仅用作私有成员变量的结构

Where to define struct only to be used as private member variable?

本文关键字:成员 变量 结构 定义 在其中      更新时间:2023-10-16

以下面的头文件为例,其中Bar是一个结构体:

class Foo
{
    ...
private:
    Bar _bar;
};

我只希望Bar可以作为Foo的私有成员变量访问。什么是正确的方式来声明和定义Bar ?

选项1:define in header?

我想避免这种情况,因为我不希望BarFoo类范围之外可用。

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.