const和静态指定符在c ++ [英] const and static specifiers in c++
问题描述
#include<iostream>
using namespace std;
class A
{
private:
const int a=9;
public:
void display()
{
cout<<a;
}
};
int main()
{
A a;
a.display();
return 0;
}
为什么不允许初始化const int a = 9。
但是如果我写常量static int a = 9编译器不显示任何错误。编写const static int a = 9的意义是什么?我应该怎么写这样?
〜
Why does initialization const int a=9 is not permitted.
But where as if i write constant static int a=9 compiler does not show any error. What is the meaning of writing const static int a=9? when should i write like this ?
~
推荐答案
使用构造函数初始化列表初始化非静态常量
Use constructor initializer list to initialize non-static constant members.
ISO C ++ 03说明了有关静态数据成员的以下事项。
ISO C++03 says the following things about static data members.
[class.static.data]
9.4.2静态数据成员
1静态数据成员不是类的子对象的一部分。只有该类的所有对象共享的静态数据成员的一个副本。
1 A static data member is not part of the subobjects of a class. There is only one copy of a static data member shared by all the objects of the class.`
2类定义中静态数据成员的声明不是并且可以是除了cv限定的空格之外的不完全类型。 staticdata成员的定义应该出现在包含成员的类定义的命名空间范围中。在命名空间范围的定义中,静态数据成员的名称应使用::运算符通过其类名限定。 `
2 The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void. The definition for a staticdata member shall appear in a namespace scope enclosing the member’s class definition. In the definition at namespace scope, the name of the static data member shall be qualified by its class name using the :: operator. `
如果静态数据成员是 const integer 或const枚举类型,它在类定义中的声明可以指定常量 - 初始化器,它应是一个整数常数表达式(5.19)。在这种情况下,成员可以出现在整数常数表达式中。 如果成员在程序中使用,并且命名空间范围定义不应包含初始化程序* ,则仍然在命名空间范围中定义。
If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a name-space scope if it is used in the program and the namespace scope definition shall not contain an initializer*.
class A
{
private:
const int a=9; //incorrect
static const int b = 10; //declaration (correct)
static const double c = 1.3 //incorrect (Only const-static int members can be initialized like that)
public:
A(): a(9){}
};
const int A::b; //definition of const-static int member
你可以取静态成员的地址if只有)它具有超类定义:
You can take the address of a static member if (and only if) it has an out-of-class definition:
class AE {
// ...
public:
static const int c6 = 7;
static const int c7 = 31;
};
const int AE::c7; // definition
int f()
{
const int* p1 = &AE::c6; // error: c6 not an lvalue
const int* p2 = &AE::c7; // ok
// ...
}
这篇关于const和静态指定符在c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!