为什么可以在类中声明静态常量成员,但不能在常量成员中声明呢? [英] Why is it possible to declare static constant member in a class but not constant member?
本文介绍了为什么可以在类中声明静态常量成员,但不能在常量成员中声明呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么可以在一个类中声明一个静态常量成员,而不是一个常量成员?
hi why is it possible to declare a static constant member in a class but not a constant member?
推荐答案
它绝对是 可以在C ++类中声明和使用非静态常量成员.
请参见此 [
It is definitely possible to declare and use a non-static constant member in C++ classes.
See this[^] form Bjarne Stroustrup''s C++ Style and Technique FAQ. :)
您的意思是在类中初始化变量吗?
static const
是一个变量,不会为该类的所有实例更改其值.
另一方面,const
变量的值对于该类的一个实例不变,但对于不同的实例可以不同.
静态const示例-
Do you mean initialize the variable in-class ?
Astatic const
is a variable that is not going to change its value for all instances of the class.
Aconst
variable on the other hand can have a value that doesn''t change for one instance of the class, but can be different for different instances.
A static const example -
class A
{
public:
static const int var = 100;
};
一个const示例-
A const example -
class A
{
public:
const int var;
A(int a) : var(a) {}
};
int main()
{
A a(10);
A b(20);
}
我想看
就像优化内存使用量一样::-D
I want to see it
just as an optimization of the memory usage... :-D
这篇关于为什么可以在类中声明静态常量成员,但不能在常量成员中声明呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文