Wednesday 15 April 2015

c++ - Avoiding redeclaration for header to source file -



c++ - Avoiding redeclaration for header to source file -

let's have 2 files foo.h , foo.cpp

foo.h

class foo { public: foo(); ~foo(); private: /* fellow member functions */ static void dothis(); /* fellow member variables */ static int x; protected: };

foo.cpp

#include "foo.h" int foo::x; void foo::dothis() { x++; }

can avoid hassle of having declare each variable in foo.cpp again? if removed line int foo::x; linker error unresolved external symbol.

is there way of doing without having type line each variable i'm planning use?

you need re-declare static variables. if create variable in class definition without making them static, can leave them there. example:

foo.h

#ifndef _foo_h_ #define _foo_h_ class foo{ private: static int i; //static variable shared among instances int o; //non-static variable remains unique among instances public: foo(); //consructor }; #endif

foo.cpp

int foo::i = 0; //only static variables can initialized when in class //no definition required non-statics foo::foo(){ //constructor code here = 0; };

the #ifndef block prevents header accidentally beingness included multiple times same source file. in case header included in header, which, if these blocks not present, result in infinite include loop , forcefulness compiler quit when counts include depth that's high.

c++

No comments:

Post a Comment