问题
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