when是一个非静态的const数据成员比const static更有用吗? [英] When is a non-static const data member more useful than a const static one?
本文介绍了when是一个非静态的const数据成员比const static更有用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C ++中有静态和非静态的 const
数据成员。
当我想要一个常数,我总是使它 static
,因为它是没有意义的有多个副本(每个类的一个实例)不能修改。我想知道为什么有非静态的 const
成员?
解决方案
ol>
static const
适用于类 const 适用于对象
例如
class Verticies {
public:
const int color;
static const int MAX_VERTICIES = 100;
积分[MAX_VERTICIES];
Verticies(int c):color(c){}
// Etc
};
这里 MAX_VERTICIES
适用于所有类型的对象 Verticies
。但不同的对象可以有不同的颜色,而且这种颜色是固定的建设
In C++ there are static and non-static const
data members.
When I want a constant, I always make it static
because it does not make sense to have multiple copies (one per each instance of the class) if the item cannot be modified. I would like to know why are there non-static const
members?
解决方案
- A
static const
applies to the class - A
const
applies to the object
E.g.
class Verticies {
public:
const int colour;
static const int MAX_VERTICIES = 100;
Point points[MAX_VERTICIES];
Verticies(int c) : colour(c) { }
// Etc
};
Here MAX_VERTICIES
applies to all objects of type Verticies
. But different objects could have different colours and that colour is fixed on construction
这篇关于when是一个非静态的const数据成员比const static更有用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文