简体   繁体   中英

How to use polymorphism with classes from different header files?

I've got class Figure in my header "figure.h":

class Figure
{
    Color color;
    std::string position;
    ...
};

and I want to define a class King in header "king.h". So in king.h I do #include "figure.h" , and write for ex:

class King : public Figure
{
     char type;
     bool checkIfTypeIsValid(std::string);
     ...
};

But this doesn't seem to work, as King doesn't recognize Figure... What should I do? And is it smart to have different headers for different inherited classes, or just lump them together in "figure.h"? Because I'll have a Queen, Bishop, etc. figures as well, which will make quite a lot of headers and impl. files..

First: you cannot derive from an unknown, or even a partially known class. In order to define King , you must first include Figure.h (supposing King is defined in a different file).

More generally, as to how to organize the code, there is no one definitive answer. Personally, in the one particular case (where the number of derived classes is well defined and strictly bound), I'd probably cut corners and define all of them in Figure.h , but there are very good arguments for using a separate header for each—if nothing else, you don't have to include the headers for the individual figures except in files where they are created. Another solution would be to use factory functions for the figures, and define the derived classes in the source file which implements the factory functions.

You need include figure.h at first.

#include<Figure.h>

class King : public Figure
{
    ...
};

Check include path for your compiler. It would be like : -I"PATH_TO_DIR_WHERE_FIGURE_H_LOCATED", without quotes.

Ensure that king.h contains #include "figure.h" or #include <figure.h> , as long as figure.h is on your include path on in the same folder as king.h . If you're on Windows, the include headers can have incorrect case. On everything else, ensure that the case is correct. Lastly, if the definition of Figure is inside a namespace, you'll have to append that:

class King : public some_namespace::Figure
{
   //....
};

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