如何在C ++中初始化一个静态const成员? [英] How to initialize a static const member in C++?

查看:163
本文介绍了如何在C ++中初始化一个静态const成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在构造函数之外初始化一个静态const值?是否可以在发现成员声明的相同位置初始化?

Is it possible to initialize a static const value outside of the constructor? Can it be initialized at the same place where member declarations are found?

class A {
private:
  static const int a = 4;
  /*...*/
};


推荐答案


如果你希望你的静态成员是任何其他类型,你必须在cpp文件中的某处定义它。

YES you can but only for int types. If you want your static member to be any other type, you'll have to define it somewhere in a cpp file.

class A{
private:
 static const int a = 4; // valid
 static const std::string t ; // can't be initialized here
 ...
 ...
};


// in a cpp file where the static variable will exist 
const std::string A::t = "this way it works";

此外,请注意,此规则已在C ++ 11中删除,特征),你可以在类成员声明中直接初始化你想要的。

Also, note that this rule have been removed in C++11, now (with a compiler providing the feature) you can initialize what you want directly in the class member declaration.

这篇关于如何在C ++中初始化一个静态const成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆