Class declaration confusion - name between closing brace and semi-colon

Deadly 提交于 2021-02-04 17:59:07

问题


class CRectangle {
    int x, y;
  public:
    void set_values (int,int);
    int area (void);
  } rect;

In this example, what does 'rect' after the closing brace and between the semi-colon mean in this class definition? I'm having trouble finding a clear explanation. Also: Whatever it is, can you do it for structs too?


回答1:


rect is the name of a variable (an object in this case).

It is exactly as if it had said:

  int rect;

except instead of int there is a definition of a new type, called a CRectangle. Usually, class types are declared separately and then used as

  CRectangle rect;

as you are probably familiar with, but it's perfectly legal to declare a new type as part of a declaration like that.

And yes, it works for structs:

  struct SRectangle { int x, y; } rect;

In fact you don't even have to give the type a name if you don't plan to use it again:

  struct { int x, y; } rect;

that's called an "anonymous struct" (and it also works for classes).




回答2:


It is an object of type CRectangle that is global or belongs to a namespace depending on the context.




回答3:


It declares an instance. Just like:

class CRectangle
{
    // ...
};

CRectangle rect;

There is no difference between a class and a struct in C++, except structs default to public (in regards to access specifiers and inheritance)




回答4:


The one and only difference between structs and classes is that structs have a public default inheritance and access and classes use private as default for both.



来源:https://stackoverflow.com/questions/2526711/class-declaration-confusion-name-between-closing-brace-and-semi-colon

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!