[023] Ning to replace the member function with Non-member and non-friend

Source: Internet
Author: User

The author spends a significant portion of this section on why it is best to use Non-member, non-friend functions.

Ideas are as follows:

Scenario: If a class is used to represent a Web browser, then we may define the following classes when we clear the cache and history:

class Web {public:    void  clearcache ();     void clearcookies ();     void clearhistory ();}

However, it is also possible that the user needs to clear the information all at once, so we define the following member function:

class Web {
Public: void cleareverything (); ...}

Of course, we can use a non-member function to do this:

void Clear (web& WB) {    wb.clearcache ();    Wb.clearcookies ();    Wb.clearhistory ();}

According to the object-oriented code requirements, the data and the functions that manipulate the array should be bundled together. That said, however, the Non-member function clear () has greater encapsulation for clear operations.

Therefore, we recommend using the Non-member function.

In practice, when class has a lot of operational functions, we often make the Class A non-member function and reside within the same namespace as the Web. Like what:

1 //header File "Web.h"2 namespaceweb{3 classweb{};4....//into the core functions, such as all non-member function that almost the customer needs5 6 }7 8 //header File "Webbrowser.h"9 namespaceweb{Ten classweb{}; One....//functions related to browser tags A  - } -  the //header File "Webcookies.h" - namespaceweb{ - classweb{}; -....//cookies-related functions +  -}

How the above formal C + + standard library is organized.

Summary

Rather, replace the member function with Non-member and non-friend. This can increase encapsulation, package elasticity, and functional extensibility.

[023] Ning to replace the member function with Non-member and non-friend

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.