C++ Basics Review 1

Forgettable properties of classes:

近期,翻看基础的《C++ Primer》,温故而知新,希望自己养成好习惯,在某一领域深耕耘,路漫漫而修远,吾将上下而求索。

1. Inline member functions of a class: There are often some smaller functions in a class that are suitable to be declared as inline functions, and member functions defined inside a class are automatically inline.

2. Mutable data members - mutable
mutable data members are never const, even if it is a member of a const object.

    class Screen {
        public:
            void some_member() const;

        private:
            mutable size_t access_ctr;
    };
    Screen::some_member() const
    {
        ++access_ctr;
    }

3. Encapsulation After
working for several months, the understanding of encapsulation is: when encapsulating a class, it is necessary to determine its functions, which interfaces are provided for external use, and which interfaces need to be hidden.
Here's a better explanation from the book:

  • Ensure that user code does not inadvertently corrupt the state of the encapsulated object;
  • The specific implementation details of the encapsulated class can be changed at any time without adjusting user-level code.

3. Re-exploration
of friends 1. Friends are not transitive
2. Member functions of friend classes can access all members including non-public members of this class

class Screen{
    friend class Window_mgr;
}

class Window_mgr{
    public:
        using ScreenIndex = std::vector<Screen>::size_type;
        void clear(ScreenIndex);

    private:
       std::vector<Screen> screens{Screen(24, 80, '')};
}
void Window_mgr::clear(ScreenIndex i)
{
    Screen &s = screen[i];
    s.contents = string( s.height * s.width, '');//Window_mgrScreen类的友元类,故可以访问 Screen类的私有成员height 和width
}

4. Recommendation: Use the constructor to initialize the value
1. If the member is const or reference, it must be initialized.
2. The difference between initialization and assignment is that initialization is to directly initialize data members, while assignment is to initialize first and then assign.

5.
Literal value constants The return value and parameters of the constexpr function are literals.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325940084&siteId=291194637