How can I declare a structure in C++ without defining it? -
i have been following tutorial @ cplusplus.com/doc/tutorial. near end of functions page, discussed prototyping function. later on, read structures. thought looked little messy, , code blocks after main method. wondered if prototype data structure. tried this:
#include <iostream> using namespace std; struct astruct; int main() { astruct structure; structure.a = 1; structure.b = 2; cout << structure.a << ", " << structure.b << "\n"; return 0; } struct astruct { int a; int b; };
but ide said "astruct not declared in scope". so, how prototype data structure bulk of can below main method?
the tutorial pages: functions data strucutres
generally reason pre-declaring structure avoiding circular references in defining structures. right solution use header, , hide structure definition in header instead:
inside astruct.h
:
struct astruct { int a; int b; };
inside main.cpp
:
#include <iostream> #include "astruct.h" using namespace std; struct astruct; int main() { astruct structure; structure.a = 1; structure.b = 2; cout << structure.a << ", " << structure.b << "\n"; return 0; }
in long run happier organizing code separate files.
i leave exercise reader protect against multiple inclusion of header using #ifdef astruct_h/#define astruct_h/#endif lines
.
Comments
Post a Comment