gpt4 book ai didi

c++ - C++ 中 struct typedef struct 的用途

转载 作者:IT老高 更新时间:2023-10-28 22:23:23 25 4
gpt4 key购买 nike

在 C++ 中可以创建一个结构:

struct MyStruct
{
...
}

还可以做以下事情:

typedef struct
{
...
} MyStruct;

但据我所知,两者之间没有明显的区别。哪个更可取?如果没有区别,为什么两种方式都存在?哪一种在风格或可读性上比另一种更好?

最佳答案

以下是两个声明/定义之间的区别:


1) You cannot use a typedef name to identify a constructor or a destructor

struct MyStruct { MyStruct(); ~MyStruct(); }; // ok

typedef struct { MyStructTD(); ~MyStructTD(); } MyStructTD; // not ok

// now consider
typedef struct MyStruct2 { MyStruct2(); } MyStructTD2; // ok

MyStructTD2::MyStruct2() { } // ok
MyStructTD2::MyStructTD2() { } // not ok

2) You cannot hide a typedef name like you can a name introduced via the class-head - or conversely if you already have a function or an object with a certain name, you can still declare a class with that name using the class-head but not via the typedef approach.

struct MyStruct { }; // ok

typedef struct { } MyStructTD; // ok

void MyStruct() { } // (1) - ok Hides struct MyStruct
void MyStructTD() { } // (2) - not-ok - ill-formed

//> Or if you flip it around, consider in a new translation unit:

void MyStruct() { } // ok
void MyStructTD() { } // ok

struct MyStruct { }; // ok
typedef struct { } MyStructTD; // Not ok

3) You cannot use a typedef name in an elaborated type specifier

struct MyStruct {  }; // ok

typedef struct { } MyStructTD; // ok

int main()
{
void MyStruct();
void MyStructTD(); // ok - new declarative region

struct MyStruct ms; // ok - names the type
struct MyStructTD ms2; // not ok - cannot use typedef-name here

}

struct AnotherStruct
{
friend struct MyStruct; // ok
friend struct MyStructTD; // not ok
};

4) You cannot use it to define nested structs

struct S { struct M; };

typedef struct { } S::M; // not ok

struct S::M { }; // ok

如您所见,两者之间存在明显差异。 typedefs 的一些怪癖是 C 兼容性的结果(这主要是我相信这两种方式存在的原因) - 在大多数情况下,在类头中声明名称更自然 C++ - 它有其优势(尤其是当你需要定义构造函数和析构函数),因此更可取。如果您正在编写需要与 C 和 C++ 兼容的代码,那么使用这两种方法都有好处。但是,如果您正在编写纯 C++,我发现在类头中指定类名更易读。

关于c++ - C++ 中 struct typedef struct 的用途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1083959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com