简体   繁体   中英

c++ initializing struct with struct pointer

While I was reading C++Primer, I came across this code

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

What does 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 destination;
struct connection;
destination dest;
connection connect(dest);

What does connection connect(destination*); line do?

It declares a function called connect , that takes a destination* and returns 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 .

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?

No.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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