当我们有一个更短的方法时,为什么我们在结构中使用typedef

Nov*_*per -5 c++ struct

当我定义一些随机结构时,例如在Visual Studio中的cpp文件中

1)    struct CAddition {
    int x, y;

    CAddition(int a, int b) { x = a; y = b; }
    int result() { return x + y; }
};
Run Code Online (Sandbox Code Playgroud)

现在,如果我定义一些结构对象

CAddition foo;
Run Code Online (Sandbox Code Playgroud)

它没有任何错误,但如果我最后使用任何别名

2) struct CAddition {

    int x, y;

CAddition(int a, int b) { x = a; y = b; }
int result() { return x + y; }
}CAddition;
Run Code Online (Sandbox Code Playgroud)

我不能简单地定义任何对象而不在定义之前使用struct

 struct CAddition foo;
Run Code Online (Sandbox Code Playgroud)

或者另一种方法是添加

typedef struct CAddition { 
Run Code Online (Sandbox Code Playgroud)

在方法2中,为了避免每次都重写struct,我的问题是这两个定义之间的区别是什么,方法1不使用更少的关键字,更容易使用在什么条件下我们应该使用结构的第二个定义.

Som*_*ude 5

随着struct CAddition { ... } CAddition;你在做两件事情:

  1. 您将结构定义CAddition为类型名称.这就是struct CAddition事情的作用.
  2. 您定义变量 CAddition.变量是结构之后的变量.

因为您定义了变量CAddition,所以不能对该类型使用该名称,因为编译器会认为您的意思是变量而不是结构.要解决这个问题,您需要使用struct CAddition明确告诉编译器您的意思是结构类型名称.


在一个不相关的注释:A struct就像一个class,不同之处在于public默认情况下所有成员都是a struct.所以你不需要a中的public规范struct.