繁体   English   中英

C ++ typedef中的struct关键字

[英]struct keyword in C++ typedef

我看着格列(Glew)的标题,遇到了一个对我提出疑问的东西:

// C
typedef struct __GLsync *GLsync;

我知道Glew是一个C库,因此不同于C ++,并且我知道这是C ++中的有效代码:

// C++
struct S { ... }; // S defined in the class name space
void f( S a ); // struct is optional

我的问题是,从C ++的typedef中删除struct关键字并将其包含在仅C ++的项目中是否安全?

typedef /*struct*/ __GLsync *GLsync;

如果没有,当我使用struct关键字而不使用typedef有什么区别?

以下形式的typedef:

typedef struct S *SPtr;

不需要先验知识相同翻译单元中的S 它假定某些结构S的前向声明和别名SPtr作为指向相同的指针类型。 但是,这:

typedef S *SPtr; // error unless S is declared earlier 

需要在声明指针别名类型之前就已经知道类型S (可能是结构)的声明。

尽管这看似微不足道,但它是pimpl惯用语的常见实现的基石。 请注意,这里没有真正涉及到typedef ,将struct MyClassImpl*为指向稍后(但在实际取消引用之前)要确定的未知“事物”的指针类型的声明很重要:

MyClass.h

#ifndef MY_CLASS
#define MY_CLASS

class MyClass
{
   ... members ...

private:
    struct MyClassImpl * m_pimpl; // note no MyClassImpl yet known
};

#endif

MyClass.cpp

#include "MyClass.h"  

// implementation formal declaration and implementation.
struct MyClassImpl
{
    ... members...
};

// MyClass implementation using the now-known MyClassImpl

该指针是否声明为:

MyClassImpl * m_pimpl;

MyClassImpl类型需要事先声明,否则会发生编译时错误。

我希望这有助于确定两种声明方法之间的关键区别。 (是的,我知道,我应该使用智能指针= P)

祝你好运。

真正的答案也许是 这取决于之前找到的其他代码。

话虽这么说,您可以完全更改此:

typedef struct __GLsync *GLsync;

对此:

struct __GLsync;
typedef __GLsync *GLsync;

如果要从typedef删除struct关键字,则必须执行以下操作:

typedef struct S { ... }__GLsync; // S defined in the class name space

那么您可以使用:

typedef  __GLsync  *GLsync;

附加问题:

如果struct已经由其他人定义,那么如何解决

 typedef struct __GLsync  *abc;
 typdef  *abc       GLsync

你可以做这样的事情

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM