C++ “const 类”是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/206998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does "const class" mean?
提问by 1800 INFORMATION
After some find and replace refactoring I ended up with this gem:
经过一番查找和替换重构后,我最终得到了这个 gem:
const class A
{
};
What does "const class" mean? It seems to compile ok.
“const 类”是什么意思?好像编译没问题。
采纳答案by 1800 INFORMATION
What does "const class" mean? It seems to compile ok.
“const 类”是什么意思?好像编译没问题。
Not for me it doesn't. I think your compiler's just being polite and ignoring it.
对我来说不是。我认为您的编译器只是出于礼貌而忽略了它。
Edit:Yep, VC++ silently ignores the const, GCC complains.
编辑:是的,VC++ 默默地忽略了常量,GCC 抱怨。
回答by Adam Rosenfield
The const
is meaningless in that example, and your compiler should give you an error, but if you use it to declare variables of that class between the closing }
and the ;
, then that defines those instances as const
, e.g.:
该const
是在例如意义的,你的编译器应该给你一个错误,但如果你用它来宣告闭幕之间的类的变量}
和;
,然后定义这些实例作为const
,例如:
const class A
{
public:
int x, y;
} anInstance = {3, 4};
// The above is equivalent to:
const A anInstance = {3, 4};
回答by Evan Teran
If you had this:
如果你有这个:
const class A
{
} a;
Then it would clearly mean that 'a' is const. Otherwise, I think that it is likely invalid c++.
那么它显然意味着'a'是const。否则,我认为它可能是无效的 c++。
回答by Matt Joiner
It's meaningless unless you declare an instance of the class afterward, such as this example:
除非你在之后声明一个类的实例,否则它是没有意义的,比如这个例子:
const // It is a const object...
class nullptr_t
{
public:
template<class T>
operator T*() const // convertible to any type of null non-member pointer...
{ return 0; }
template<class C, class T>
operator T C::*() const // or any type of null member pointer...
{ return 0; }
private:
void operator&() const; // Can't take address of nullptr
} nullptr = {};
An interim nullptr
implementation if you're waiting for C++0x.
nullptr
如果您正在等待 C++0x,则是一个临时实现。
回答by dr__noob
Try compiling it with GCC, it will give you below error:error: qualifiers can only be specified for objects and functions.
尝试用 GCC 编译它,它会给你以下错误:error: qualifiers can only be specified for objects and functions.
As you can see from the error that only objects(variables, pointers, class objects etc.) and functions can be constant. So try making the object as constant, then it should compile fine.const class A {};
const A a ;
从错误中可以看出,只有对象(变量、指针、类对象等)和函数可以是常量。因此,尝试将对象设为常量,然后它应该可以正常编译。const class A {};
const A a ;