编译时出现错误"collect2:ld 返回 1 个退出状态"

Error "collect2: ld returned 1 exit status" while compiling

本文关键字:返回 状态 退出 ld collect2 错误 编译      更新时间:2023-10-16

当我构建以下源代码时:

#include <stdio.h>
class Heap
{
    public:
        Heap()
        {
            printf("Heap()");
        }
        void* print()
        {
            printf("This is Heap Print");
        }
};
class DvHeap : public Heap
{
    public:
        DvHeap():Heap()
        {
            printf("DvHeap()n");
        };
};
template<class T>
class base
{
    public:
        void* operator new(size_t size)
        {
            printf("base()n");
            return T::printit().print();
        }
};
template<class T>
class derived : public base<derived<T> >
{
    static  DvHeap xx;
    public:
        static Heap& printit()
        {
            printf("DvHeap()n");
           return xx;
        }
}; 
int main()
{
    //DvHeap *pH = new DvHeap(1);
    derived<DvHeap> *pD = new derived<DvHeap>;
    return 0;
}

我收到以下错误:

[debdghos]$ g++ Ctest.cpp -o test

/

tmp/ccM7XI3u.o:在函数中 derived<DvHeap>::printit()': Ctest.cpp:(.text._ZN7derivedI6DvHeapE7printitEv[derived<DvHeap>::printit()]+0xf): undefined reference to 派生::xx'收集2:LD 返回 1 个退出状态

谁能告诉我为什么会这样?该代码用于学习目的。

谢谢

您应该在类外部初始化静态成员。

template<typename T>
DvHeap derived<T>::xx;

完整代码:

include <stdio.h>
class Heap
{
    public:
        Heap()
        {
            printf("Heap()");
        }
        void* print()
        {
            printf("This is Heap Print");
        }
};
class DvHeap : public Heap
{
    public:
        DvHeap():Heap()
        {
            printf("DvHeap()n");
        };
};
template<class T>
class base
{
    public:
        void* operator new(size_t size)
        {
            printf("base()n");
            return T::printit().print();
        }
};
template<class T>
class derived : public base<derived<T> >
{
    static  DvHeap xx;
    public:
        static Heap& printit()
        {
            printf("DvHeap()n");
           return xx;
        }
}; 
    template<typename T>
    DvHeap derived<T>::xx;
int main()
{
    //DvHeap *pH = new DvHeap(1);
    derived<DvHeap> *pD = new derived<DvHeap>;
    return 0;
}

在你错的地方阅读以下内容:http://www.learncpp.com/cpp-tutorial/811-static-member-variables/