GCC 错误:嵌套名称说明符中使用的类型"claculator"不完整

GCC error: incomplete type 'claculator' used in nested name specifier

本文关键字:类型 claculator 嵌套 错误 说明符 GCC      更新时间:2023-10-16

我开发了一个库,当我用GCC(在Windows中使用CodeBlocks)编译我的代码时,源代码不编译,出现此错误:

错误:嵌套名称说明符中使用了不完整的类型"计算器"。

我写了一个示例代码,正好产生这个错误:

class claculator;
template<class T>
class my_class
{
    public:
    void test()
    {
        // GCC error: incomplete type 'claculator' used in nested name specifier
        int x = claculator::add(1, 2);
    }
    T m_t;
};
// This class SHOULD after my_class.
// I can not move this class to top of my_class.
class claculator
{
    public:
    static int add(int a, int b)
    {
        return a+b;
    }
};
int main()
{
    my_class<int> c;
    c.test();
    return 0;
}

如何解决这个错误?

请注意,我的源代码在Visual Studio中编译成功了。

谢谢。

很简单。在之后定义test() calculator类的定义如下:

class calculator;
template<class T>
class my_class
{
    public:
    void test(); //Define it after the definition of `calculator`
    T m_t;
};
// This class SHOULD after my_class.
// I can not move this class to top of my_class.
class calculator
{
    public:
    static int add(int a, int b)
    {
        return a+b;
    }
};
//Define it here!
template<class T>
void my_class<T>::test()
{
     int x = calculator::add(1, 2);
}
这样,编译器在解析test()定义时就知道calculator完整的定义。