简体   繁体   中英

Including header files (including themselves)

lets say I have 3 classes. 1 base class and two derived classes. if I put these 3 in separate header files, how do I properly include them all so they all see each other? Ill post some simple sample code I found:

Polygon.h

// Base class


class Polygon 
{
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b;}
 };

triangle.h

class Triangle: public Polygon 
{
  public:
    int area ()
      { return width * height / 2; }
};

rectangle.h

class Rectangle: public Polygon 
{
  public:
    int area ()
      { return width * height; }
};

main.ccp

int main () 
{
  Rectangle rect;
  Triangle trgl;
  rect.set_values (4,5);
  trgl.set_values (4,5);
  cout << rect.area() << '\n';
  cout << trgl.area() << '\n';
  cin.get();
  return 0;
}

I know What includes I will need I just don't know how to properly arrange them in order to make this work cleanly, thank you!

Quite clearly your Rectangle and Triangle classes require Polygon to be defined before them, so the order should be:

#include "Polygon.h"
#include "Rectangle.h"
#include "Triangle.h"

The Last two can be in any order as they don't depend on each other.

EDIT:

In order to clarify why this works, when you write #include "file.h" , the contents of the file file.h are simply copied at the location of the include line. So, now to get the order right, just think what order will you keep when defining all classes in the main.cpp file itself and that's what the order of header files should be.

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