简体   繁体   English

C ++使用结构指针初始化结构

[英]c++ initializing struct with struct pointer

While I was reading C++Primer, I came across this code 在阅读C ++ Primer时,我遇到了这段代码

struct destination;
struct connection;
connection connect(destination*);

What does connection connect(destination*); connection connect(destination*);是什么connection connect(destination*); line do? 行吗? and how come it compiles fine even though it's passing the struct name? 以及即使传递了结构名称,它怎么也可以正常编译? Aren't you supposed to initialize the struct to variable then pass that like so? 您不是应该将struct初始化为变量,然后像这样传递吗?

struct destination;
struct connection;
destination dest;
connection connect(dest);

What does connection connect(destination*); connection connect(destination*);是什么connection connect(destination*); line do? 行吗?

It declares a function called connect , that takes a destination* and returns connection . 它声明了一个名为connect的函数,该函数接受destination*并返回connection

In this declaration, a name is not provided for the parameter (which, though not particularly helpful to the reader, is valid). 在此声明中,没有为参数提供名称(尽管对读者没有特别帮助,但该名称是有效的)。 Presumably, that'll be provided when the function is defined , like so: 大概是在定义函数时提供的,就像这样:

connection connect(destination* ptr)
{
   connection conn;
   // do something with conn and ptr
   return conn;
};

The rest of the book's code snippet (the part that you did not quote) shows a call to the function connect , from within another function called f . 本书的其余代码片段(您未引用的部分)显示了从另一个名为f的函数中对connect函数的调用。

Function declarations were covered six chapters prior. 函数声明在前六章中进行了介绍。

how come it compiles fine even though it's passing the struct name? 即使传递了结构名称,它怎么也可以正常编译?

Because that's what you're supposed to do in a function declaration. 因为那是您应该在函数声明中执行的操作。

Aren't you supposed to initialize the struct to variable then pass that like so? 您不是应该将struct初始化为变量,然后像这样传递吗?

No. 没有。

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

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