您的位置:首页 > 编程语言 > C语言/C++

c++11 成员变量初始化

2016-10-31 20:24 239 查看
但是在C++11中,我们可以利用类内初始化:

int j = 15;
class Bclass
{
private:
int f = 100;
float g = 200.0;
const float h = 30.0;
const int a=10;
//  const int array[20];
//  int thesecondarray[20] = { 0 };
int &b=j;
int &k = f;
static int c;
static const int d=30;
static const float e;
public:
Bclass()
{
//  array[20] = { 0 };       注释去掉有错误
//thesecondarray[20] = { 0 };
}
void print()
{
cout << a << " "
<< b << "  "
<< c << "  "
<< d << "  "
<< e << "  "
<< f << "  "
<< g << "  "
<< h << "  "
<< k << endl;
//for (int i = 0; i < 20; ++i)
//cout << array[i] << "  ";
//for (int i = 0; i < 20; ++i)
//cout << thesecondarray[i] << "   ";
}
};
int Bclass::c = 20;
const float Bclass::e = 40.0;

可以看到基本类型不用多说,可以在类内初始化。在这里我们重点看const 与static,引用,以及数组。

const  的int 与float都能在类内初始化。但是static还是只有static const int 能在类内初始化,其他的static 还是能在类外初始化。

而引用则可以在类内初始化。而无论是const 数组还是非const 数组,都不能在类内显示初始化。

原贴:http://blog.csdn.net/u014120684/article/details/24853127
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: