Friday, 15 March 2013

How can I declare a structure in C++ without defining it? -


I'm following a tutorial on this. Near the end of the Functions page, it discusses a function prototype. Later, I read about the structures. I thought it looks a bit messy, and I like my code block after my main method. So I wonder if I can prototype a data structure. I tried to do this:

  #include & lt; Iostream & gt; using namespace std; Structure architecture; Int main () {aStruct structure; Structure A = 1; Structure.b = 2; Cout & lt; & Lt; Structure A & LT; & Lt; "," & Lt; & Lt; Structure.b & lt; & Lt; "\ N"; Return 0; } Straight {int a; Int b; };  

But my IDE said that "the extract was not declared in this area" So, how do I prototype a data structure, so that its main part is less than the main method Ho?

Tutorials page:

To pre-format the structure Generally the only reason is to avoid circular references in defined structures. The correct solution is to use the header, and instead hide the structure definition in a header:

inside astrct.h :

  Struct aStruct {Int a; Int b; };  

inside main.cpp :

  #include & lt; Iostream & gt; # Include "astrct.h" using the namespace std; Structure architecture; Int main () {aStruct structure; Structure A = 1; Structure.b = 2; Cout & lt; & Lt; Structure A & LT; & Lt; "," & Lt; & Lt; Structure.b & lt; & Lt; "\ N"; Return 0; }  

In the long run, you will be very happy to organize your code in different files properly.

I will leave it as an exercise to preserve the reader properly, #ifdef ASTRUCT_H / # defined ASTRUCT_H / # endif lines .

Against many inclusion of the header,

No comments:

Post a Comment