简体   繁体   English

为什么我们再次从 struct 对象创建 struct 变量?

[英]why we are again creating struct variable from struct object?

I am beginner in c++.我是 C++ 的初学者。 Here is my doubt why in this program they are again creating struct variable from the previously created struct object ?这是我的疑问,为什么在这个程序中他们再次从以前创建的结构对象创建结构变量? Here is the example:这是示例:

typedef struct prog1
{

int a,b;

}*obj1;

int main()
{

obj1 moc=new prog1(); // why again creating object for *obj1 object?
moc->a=10;  // why dont we use obj1 -> a=10;

}

thanks谢谢

obj1 is not an object but a type definition, because it is part of the typedef definition. obj1不是对象而是类型定义,因为它是typedef定义的一部分。 Namely, it is a type of prog1* (a pointer to prog1 ).即,它是一种prog1* (指向prog1的指针)。 The obj1 moc declares a variable of this type, ie moc is a pointer to prog1 . obj1 moc声明了一个这种类型的变量,即moc是一个指向prog1的指针。

To make it more clear use an alias declaration instead of the typedef definition.为了更清楚地使用别名声明而不是 typedef 定义。

struct prog1
{

int a,b;

};

using obj = struct prog1 *;

So the name obj is an alias for the type struct prog1 * .所以名称obj是类型struct prog1 *的别名。 obj is not a variable. obj不是变量。

So in this declaration所以在这个声明中

obj1 moc; 

there is defined the variable moc with the type obj .定义了类型为obj的变量moc This declaration is equivalent to the following declaration此声明等效于以下声明

prog1 *moc;

That is there is declared a pointer of the type prog1 * .也就是说,声明了一个prog1 *类型的指针。

Pay attention to that the pointer is not initialized.注意指针没有初始化。 So it has indeterminate value.所以它具有不确定的价值。 As a result the following statement结果是下面的语句

moc->a=10;

invokes undefined behavior.调用未定义的行为。

you don't need to use typedef before struct.您不需要在 struct 之前使用typedef you can directly use prog1 as a type.您可以直接使用 prog1 作为类型。 like this:像这样:

struct prog1 {
    int a,b;
} obj1;   //<---create right away the obj1.

int main() {
   prog1 obj2;  //<---another object created.
   prog1 *pObj = new prog1();

   obj1.a = 10;
   obj2.a = 20;
   pObj->a = 30;
   //...
}

or you don't even need the prog1 struct name.或者您甚至不需要prog1结构名称。 like this:像这样:

struct {
    int a,b;
} obj1, obj2, *pObj;   //<---obj1 and obj2 already has allocated space for data.

int main() {
   pObj = new prog1();  //<---allocate data space that will be pointed by pObj.

   obj1.a = 10;
   obj2.a = 20;
   pObj->a = 30;
   //...
}

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

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