如何在C++头文件中声明typedef

Com*_* 10 1 c++ typedef header class

我想知道是否有人可以在没有重组的情况下提供建议来解决这种情况:我有一个包含类声明的标题,并声明了它通过引用/指针使用的一些类,这显然是很好的做法,而不仅仅是包括这些类的标题.

struct Foo;

struct Bar;

struct MyStruct
{
    void doIt( const Foo* foo );

    void doIt( const Bar* bar );
};
Run Code Online (Sandbox Code Playgroud)

但是,虽然在上面的示例中,Foo是一个类,但Bar实际上是一个类的typedef,如下面的粗略示例所示:

#include <fd_ex.h>

struct Foo
{
   int a;
};

struct Bar_
{
   int a;
};

typedef Bar_ Bar;
Run Code Online (Sandbox Code Playgroud)

这会导致一些问题,因为预定义struct Bar显然不正确 - Bar不是结构:

"fd_ex.cpp", line 13: Error: Multiple declaration for Bar.
"fd_ex.cpp", line 19: Error: The name Bar is ambiguous, Bar and Bar.
2 Error(s) detected.
Run Code Online (Sandbox Code Playgroud)

Bar_如果可能的话,我不想暴露,主要是因为在现实生活中这可能比这个例子复杂得多.

但是,如果我无法控制 struct声明和typedef Bar,是否有任何技术可以在标题中使用MyStruct以保持预先声明的精神Bar

Jan*_*rny 5

我不确定它在C++中是否完全相同,但在C中,我经常声明"不透明"结构,它在头文件中(让我们说mystruct.h)具有:

typedef struct MyStruct_ MyStruct;

// + function prototypes using MyStruct*
Run Code Online (Sandbox Code Playgroud)

然后我可以使用指针MyStruct而不知道它是什么,例如:MyStruct *x;,但不是MyStruct x[3];(因为编译时不知道MyStruct的大小)

然后在源文件中mystruct.c我定义了struct MyStruct_.

所以我认为你可以尝试替换:

class Bar;
Run Code Online (Sandbox Code Playgroud)

有:

typedef struct Bar_ Bar;
Run Code Online (Sandbox Code Playgroud)

(你可能只是typedef Bar_ Bar;在c ++中说)