const和静态const的区别是什么?
What is the difference of const and static const?
以下语句都是有效的:
static const A = 2;
const B = 3;
声明第一个和第二个有什么区别?
如果在类中声明static
const,则可以从类和类的任何实例访问它,因此所有这些都将共享相同的值;单独的const对于该类的每个实例都是互斥的。
给定类:
class MyClass {
public:
static const int A = 2;
const int B = 4;
};
你可以这样做:
int main() {
printf("%d", MyClass::A);
/* Would be the same as */
MyClass obj;
printf("%d", obj.A);
/* And this would be illegal */
printf("%d", MyClass::B);
}
在Ideone上查看
Static表示整个类只共享1个const,而非Static表示类的每个实例都单独拥有该const。
的例子:
class A{
static const a;
const b;
}
//Some other place:
A m;
A n;
对象m和n具有相同的a,但不同的b。
相关文章:
- 初始化或分配空字符串文字到指向 C 中的 char 的指针或指向 C++ 中 const char 的指针的原因是什么
- 在C++17中,引用const字符串的语义应该是什么
- 在只读(即 const)访问器上执行结构化绑定的最佳实践是什么?
- "char const * name() const _WEBSOCKETPP_NOEXCEPT_TOKEN_ {"剂量是什么意思
- 语法问题:"char [5] const &"是什么意思?
- 'note: 候選人: Volume& Volume::operator=(const Volume&)'.这个错误是什么?
- 在下面函数的返回中添加 const 限定符的重要性是什么?
- int(int)& 或 int(int) const &是什么类型?
- 这个(const vector<vector<int> > &A)"代码段是什么意思?
- classname functionname(const classname & objectname)是什么意思?
- const自动参考绑定到(NULL)指针 - 实际类型是什么
- "const char(&a)[N]"是什么意思?
- "inline operator T*() const"是什么意思?
- 过载"operator X*() const"是什么意思?
- const T& value() const 是什么意思?
- 函数头后面的const是什么意思
- const T*const是什么意思
- 函数声明(虚拟无效打印标记表() const = 0;)中函数名称后"Type Qualifier (const)"是什么意思?
- 在C++重载运算符时"const"是什么意思
- C++:"T const *[]"是什么意思?