0

当我构建以下源代码时:

#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 测试

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

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

谢谢

4

2 回答 2

1

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

template<typename T>
DvHeap derived<T>::xx;
于 2013-10-31T11:57:27.093 回答
0

完整代码:

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/

于 2013-10-31T13:57:57.500 回答