简体   繁体   中英

using same C++ access specifiers multiple times

What is the purpose of declaring multiple "public" specifiers over and over again when the next line is just right below it, or few lines below it. I can understand this is requirement when the codes modified the attribute of some identifiers, ie, those that are buried within a macro (hence changing the access attributes within the macro, so we need to "redefined" coming out of the macro), or when we have many identifiers per access specifier section. But what is the purpose of keep using "public", "public", over and over again?

Code ...

class CDrawMFCView : public CView
{
protected: // create from serialization only
    CDrawMFCView();
    DECLARE_DYNCREATE(CDrawMFCView)

// Attributes
public:
    CDrawMFCDoc* GetDocument() const;

// Operations
public:

// Overrides
public:
    virtual void OnDraw(CDC* pDC);  // overridden to draw this view
    virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
  // etc.,

};

For starters, it's not necessary for how the code is NOW, it's necessary because the code sections may:

  • become a lot longer
  • be cut-and-pasted into a different order, or even into a different class, or copied into a new class
  • have some sections change the access specifier without the previous or following ones changing

If you relied the section having the same access specification as the previous section, vry very often you (or you, six months from now, or someone else) would forget to change it when the code changed, and then the code would be wrong.

It could be useful when looking at a class with more methods than lines on your screen, so you just look at, say

...
void f();
void g();
void h();
...

By repeating public: a few times you could remind people that all these are public (of course, having more methods than lines in your terminal either means your terminal is a bit small or the class is too big).

There is no language purpose to doing that. I think it is bad style. But some people like to divide up everything of a particular kind into a section, and then divide the section into public/protected/private areas. Then when they don't happen to have anything but public elements, then the public keyword gets repeated redundantly.

I think its dumb. But some people find it useful to organize their code this way.

There is only one formal reason: data members between access specifiers are ordered sequentially in memory, but data members across access specifiers may be reordered in memory.

class Foo {
  public:
    int a;
    int b; // Must come after a
  public:
    int c; // Does not have to come after a and b.
};

The second public: gives more room for the optimizer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM