gpt4 book ai didi

c++ - 类 ctor 中未定义的模板静态变量

转载 作者:太空宇宙 更新时间:2023-11-04 11:57:03 24 4
gpt4 key购买 nike

我已经定义了下面的类层次结构,我的目的是设计一个允许我迭代枚举对象的通用类(不幸的是,不允许使用 C++11)。类定义和测试程序为:

// base.h

#include <set>

template <typename T>
class Base
{
protected:
explicit Base(int value);
typedef typename std::set< Base<T>* > instances;
static instances s_instances;
int value_;


public:
int get_value() const { return value_ ; }
};

template <typename T>
Base<T>::Base(int value): value_(value)
{
s_instances.insert(this);
}

//派生.h

#include "base.h"

class Derived : public Base<Derived>
{
protected:
explicit Derived(int value): Base<Derived>(value) { }

public:
static const Derived value1;
};

//测试.cc

#include "derived.h"


template<>
Base<Derived>::instances Base<Derived>::s_instances;

const Derived Derived::value1(1);

int main(int argc, char *argv[])
{

using std::cout;
using std::endl;

cout << Derived::value1.get_value() << endl;

}

使用 g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 编译时,出现以下链接错误:"

g++ test.cc -o test
/tmp/ccOdkcya.o: In function `Base<Derived>::Base(int)':
test.cc:(.text._ZN4BaseI7DerivedEC2Ei[_ZN4BaseI7DerivedEC5Ei]+0x28): undefined reference to `Base<Derived>::s_instances'
collect2: ld returned 1 exit status

任何人都可以建议我在上面的代码中缺少什么吗?

谢谢!

最佳答案

静态数据成员在类定义中声明,在类定义之外定义。像这样:

// header:
class C {
static int i;
};

// source:
int C::i = 17;

使用模板,您通常不会在源文件中放置任何代码,因此定义位于标题中:

// header:
template <class T>
class C {
static int i;
};

template <class T>
int C<T>::i = 17;

关于c++ - 类 ctor 中未定义的模板静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15802802/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com