c++ - 即使使用前向声明也会出现未定义的类型错误

标签 c++ header-files forward-declaration circular-reference

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

使用以下代码(包含前向声明),我期望它能够构建,但是我收到此错误:

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

标题.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

标题2.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

显然我错过了一些东西。有人可以指出我为什么会收到此错误的正确方向吗?

最佳答案

You can only get away with forward declare if you have pointers or references 。由于您正在使用该类的特定方法,因此您需要完整包含。

但是,根据您当前的设计,您存在循环依赖。更改 Header2 文件以删除 "Header.hpp" 并转发 sample_class 声明以解决循环依赖关系。

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

关于c++ - 即使使用前向声明也会出现未定义的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32701467/

相关文章:

c++ - 实例化一个类模板并调用它的方法

c++ - 模板函数中使用的类的前向声明不是由 clang++ 编译的

c++ - 如何在 C++ 中为前向声明类型实现一元运算符重载?

c++ - WIN32, C++ : Is it possible to animate a window without hiding it?

c - debian中C头文件的位置

c++ - 如何修复 "GStreamer-CRITICAL **: gst_sample_get_buffer: assertion ' GST_IS_SAMPLE(示例 )' failed"

c++ - 什么时候使用静态库需要头文件?

c++ - 错误 : request for member which is of non class type

c++ - 使用 OpenMP 并行化 C++ 代码,并行计算实际上更慢

c++ - 参数化下一个池不可能用于池对象的类层次结构?