开发者社区> 问答> 正文

C++模板类里的静态成员问题? 400 报错

C++模板类里的静态成员问题? 400 报错

    这两天没事找了本《STL源码剖析》看下,可是刚看开头就出问题了,(本人菜鸟)特来请教

问题是这样的,书中有个测试stl_config.h中的各种组态问题,第一个例子

#include <iostream>
using namespace std;

template <typename T>
class testClass
{
public:
	static int _data;
};

int testClass <int>::_data = 1;	//这里出错
int testClass <char>::_data = 2;

int main(int argc, char *argv[])
{
	cout << testClass< int >::_data << endl;
	cout << testClass< char >::_data << endl;
	return 0;
}

在初始化静态变量是出错了

11 5  [Error] specializing member 'testClass<int>::_data' requires 'template<>' syntax

不明白为何出错,必须写为下面这样吗?

template <typename T>
int testClass <T>::_data = 1;

如果是,那岂不是书中出错?(我是菜鸟,觉得这么有名的书,估计没错吧)特来请教!!





展开
收起
爱吃鱼的程序员 2020-06-04 15:17:12 912 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB
    template<> int testClass <int>::_data = 1; 

    template<> int testClass <char>::_data = 2;

    这样就行了。可能作者的编译器与你的不一样。

    template是编译器差异化比较大的地方。也是我不喜欢C++的原因之一。

    template把事情搞得非常之复杂。


    ######谢谢 原来这样!好吧 学习了!!######你模板中类型T体现在哪里?######回复 @w_xuexi : 净信书不如无书######必须给嘛?直接用int实例化,不行?还有就是这代码是书上的!######顶一个,g++也遇到这个问题,OC上,投支持票还要积分。。。
    2020-06-04 16:20:52
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
使用C++11开发PHP7扩展 立即下载
GPON Class C++ SFP O;T Transce 立即下载
GPON Class C++ SFP OLT Transce 立即下载