本文介绍了未定义类型错误,即使具有前向声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读循环引用和前向声明.我确实知道在头文件中包含实现不是一个好的设计实践.但是我正在尝试,无法理解这种行为.

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

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

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.

推荐答案

您如果您有指针或引用,则只能使用前向声明..由于您使用的是该类的特定方法,因此需要完整的包含.

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.

但是,对于当前的设计,您具有循环依赖关系.更改Header2文件以删除"Header.hpp"并转发sample_class的声明以解决循环依赖性.

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

这篇关于未定义类型错误,即使具有前向声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 18:29