微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C未引用类的静态变量

在以下程序中打印“Here”:
#include <iostream>
class Base
{
  static bool temp;
  static bool initTemp()
  {std::cout<<"Here\n";return true;}
};

bool Base::temp = Base::initTemp();

class Derived : public Base
{};

int main() {int a;std::cin>>a;}

在以下程序中,“此处”未打印:

#include <iostream>
template <class T>
class Base
{
  static bool temp;
  static bool initTemp()
  {std::cout<<"Here\n";return true;}
};

template <class T>
bool Base<T>::temp = Base<T>::initTemp();

class Derived : public Base<int>
{};

int main() {int a;std::cin>>a;}

在这两种情况下,Base都不会被引用.唯一的区别是在第二种情况下它是一个模板类.谁能向我解释为什么会出现这种情况.我正在使用VS 2012.

解决方法

In both cases Base is never referenced.

这正是您没有看到任何打印到标准输出的原因.

除非使用该数据成员,否则不会实例化类模板的静态数据成员的定义;与成员函数一样,类模板的静态数据成员的定义也是按需实例化的.

这在C 11标准第14.7.1 / 1段中有详细说明:

[…] The implicit instantiation of a class template specialization causes the implicit
instantiation of the declarations,but not of the deFinitions or default arguments,of the class member functions,
member classes,scoped member enumerations,static data members and member templates. […]

由于您的客户端代码从不引用Base<> :: temp,因此无需构造和初始化它.

作为附注,这个签名:

void main()

无效(标准)C.如果要编写可移植代码,main()的返回类型应始终为int.

原文地址:https://www.jb51.cc/c/118749.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐