What does “const class” mean?

2019-02-04 01:06发布

After some find and replace refactoring I ended up with this gem:

const class A
{
};

What does "const class" mean? It seems to compile ok.

标签: c++ class const
5条回答
淡お忘
2楼-- · 2019-02-04 01:35

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.

查看更多
Anthone
3楼-- · 2019-02-04 01:46

What does "const class" mean? It seems to compile ok.

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.

查看更多
疯言疯语
4楼-- · 2019-02-04 01:50

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 class A
{
public:
    int x, y;
}  anInstance = {3, 4};

// The above is equivalent to:
const A anInstance = {3, 4};
查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-02-04 01:51

Try compiling it with GCC, it will give you below error:
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 ;

查看更多
再贱就再见
6楼-- · 2019-02-04 01:56

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++.

查看更多
登录 后发表回答