Is this possible in C++? toString(ClassName* class)

后端 未结 4 666
天涯浪人
天涯浪人 2021-01-26 05:11

I\'d like to use toString with class argument, but for some reason there is an error. The code is:

Animal.h

#include \"Treatment.h\"
#in         


        
相关标签:
4条回答
  • 2021-01-26 05:40

    You include Animal.h in Treatment.h before the class Treatment is defined, that's why you're getting the error.

    Use forward declaration to solve this:

    In Animal.h add line

    class Treatment;
    
    0 讨论(0)
  • 2021-01-26 05:43

    There are a few problems with your code. First of all, Animal.h should have an include guard as Treatment.h has:

    #ifndef ANIMAL_H
    #define ANIMAL_H
    
    // Your code here
    
    #endif
    

    I'd also suggest that you give a longer name to Treatment.h's guard, you'll reduce the risk of using the same name elsewhere.

    Using guards will ensure that you don't have a circular inclusion. Still you do have a circular dependency because the Treatment class needs to know about the Animal class and vice versa. However, as in both cases you used pointers to the other class, the full definitions are not required and you can - should, actually - replace in both header files the inclusion of the other with a simple declaration. For instance in Animal.h remove

    #include "Treatment.h"
    

    and add

    class Treatment;
    

    Both Treatment.cpp and Animal.cpp must include both Treatment.h and Animal.h.

    0 讨论(0)
  • 2021-01-26 05:59

    You've not used std namespace in both header files.

    So, use std::string instead of string. Because string is defined in std namespace.

    Simillarly use std::vector instead of vector.

    0 讨论(0)
  • 2021-01-26 06:03
    // Animal.h
    // #include "Treatment.h"   remove this
    
    class Treatmemt;    // forward declaration
    
    class Animal
    {
        ...
    };
    

    In your version, Treatment.h and Animal.h include each other. You need to resolve this circular dependency using forward declaration. In .cpp files, include all necessary h-files.

    0 讨论(0)
提交回复
热议问题