C ++ header file multiple inclusion

I have a problem with repeatedly including the header file in C ++ code.

For example, I have three classes X, Y, Z. X and Y are derived from the base class Z. And I want to create an instance of X in Y. The code will look like this.

class Z { …some code… };

class X: public Z { …some code… };  //here #include header of class Z added

class Y: public Z  //here #include header of class Z added as well as of X class
{
private:
   X* mX;    //instance of X 

   …some code…
};

Thus, in this plural definition of all methods of the base class arises. How can I deal with this problem?

+5
source share
4 answers

Using "enable guards" ( Wikipedia link )

#ifndef MYHEADER_H
#define MYHEADER_H

// header file contents go here...

#endif // MYHEADER_H

, C ++. MYHEADER_H - , , CustomerAccount, CUSTOMERACCOUNT_H.


/ . Z include:

#ifndef Z_H
#define Z_H

// Code of Z class

#endif Z_H

X Y z.h - .cpp, x.h, y.h, .

, C ++ , , (.c .cpp) , . "" , include .

+8

#pragma once Once . ( #ifndef, #define, #endif).

+3

, include guard . :

// within some_header.h
#ifndef SOME_HEADER_H
#define SOME_HEADER_H

// stuff goes here

#endif

, , . .

, , . , , . .

, . :

#define _SOME_HEADER_H__

. , , , , , .

+2

.

//MYCLASS.h
#ifndef _MYCLASS_H_
#define _MYCLASS_H_

class CMyClass
{
public:
    CMyClass();
}

#endif //_MYCLASS_H_
-1

All Articles