Undefined type error even with forward declaration

不问归期 提交于 2019-12-25 00:48:26

问题


I was reading up on circular references and forward declarations. I do understand that it is not a good design practice to have implementations in a header file. However I was experimenting and could not understand this behavior.

With the following code (containing the forward declarations) I expected it to build, however I get this error:

Error   1   error C2027: use of undefined type 'sample_ns::sample_class2'

Header.hpp

#ifndef HEADER_HPP
#define HEADER_HPP
#include "Header2.hpp"
namespace sample_ns
{
    class sample_class2;
    class sample_class{
    public:
        int getNumber()
        {       
            return sample_class2::getNumber2();
        }
    };
}
#endif

Header2.hpp

#ifndef HEADER2_HPP
#define HEADER2_HPP
#include "Header.hpp"
namespace sample_ns
{
    class sample_class;
    class sample_class2{
    public:
        static int getNumber2()
        {
            return 5;
        }
    };
}
#endif

Obviously I am missing on something. Can someone point me in the right direction as to why am I getting this error.


回答1:


You can only get away with forward declare if you have pointers or references. Since you are using a specific method of that class, you need a full include.

However with your current design, you have a circular dependency. Change your Header2 file to remove the "Header.hpp" and forward declare of sample_class to resolve the circular dependency.

#ifndef HEADER2_HPP
#define HEADER2_HPP
namespace sample_ns
{
    class sample_class2{
    public:
        static int getNumber2()
        {
            return 5;
        }
    };
}
#endif


来源:https://stackoverflow.com/questions/32701467/undefined-type-error-even-with-forward-declaration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!