superworm1 2016-11-05 07:32 采纳率: 0%
浏览 1303

C++模版类的静态成员变量没有初始化

 class BB
{
public:
BB()
{
printf("BB Creator\n");
fflush(stdout);
}
virtual void DoNothing()
{}
};
typedef BB* (*CreateA)();
CreateA creata = 0;
template<class T>
class A
{
public:
A()
{
printf("A Creator\n");
fflush(stdout);
creata = Create;
}
static BB* Create()
{
return new T();
}
void DoNothing(){}
};
template<class T>
class B : public BB
{
public:
B()
{
printf("B Creator\n");
fflush(stdout);
}
public:
virtual void DoNothing()
{
a.DoNothing();
}
public:
static A<T> a;
};
template<class T>
A<T> B<T>::a;
class C :public B<C>
{
public:
//C() {} 如果加上这句就对了 但是去掉以后似乎父类的构造函数都被优化掉了
};
class D
{
public:
void DFunc()
{
bb = (*creata)();
}
public:
BB* bb;
};
int main()
{
D d;
d.DFunc();
return 0;
}

如果在VS下编译是可以正确执行的
在GCC下则不行 因为作为静态成员的A B::a;没有生成, A的构造函数没有被调用, creata 则为空指针

  • 写回答

1条回答 默认 最新

  • devmiao 2016-11-06 01:02
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog