C ++ basic Tutorial: youyuan class and object-oriented

Source: Internet
Author: User

C ++ basic Tutorial: youyuan class and object-oriented

Since the companies preparing for entry soon hope to switch to C ++, they have recently started C ++ learning step by step. Then this series of articles will explore the language features of C ++ and compare the design philosophy between different languages (such as Java, Scala, Python, And Go, at the same time, I hope I can give some advice from the experts. I recently touched on the concepts of friend functions and friends classes in the learning process. In the first article, let's talk about the concepts of friends.

1. youyuan function:

First, let's briefly introduce the concept of youyuan.
In C ++, the friend function of a class is defined outside the class, but it has the right to all private members and protected members of the category. Although the prototype of the friend functions has appeared in the class definition, the friend functions are not member functions. Youyuan can be a function called youyuan function; youyuan can also be a class called youyuan class.

Let's look at the previous code to see how the functions and the membership classes are used:

# Include <iostream> using namespace std; class Box {public: Box (double l, double B, double h) {length = l; breadth = B; height = h ;} friend class A; friend voidboxPrintBox (Box & box); private: double length; double breadth; double height ;}; // youyuan function, youyuan function is not a member function voidboxPrintBox (Box & B) {cout <B. height <"" <B. length <"" <B. breadth <endl;} // youyuan class A {public: voidprintBox (Box & B) {cout <B. height <"" <B. length <"" <B. breadth <endl ;}}; intmain () {Box box (, 3); // you can access the private variable boxPrintBox (Box) of the box class ); // You can also access the private variable A a; a. Of the Box class. printBox (box); return 0 ;}

The code above shows that both the youyuan function and the youyuan class can directly access the private variables of the object. Next, let's analyze the features of the functions.

  • 1. Why do we need to introduce a friend function:
    Reduces system overhead and improves efficiency when data is shared between classes. Specifically, to allow other class member functions to directly access the private variables of the class. That is, allow external classes or functions to go to the private variables and protection variables of the category class, so that the two classes share the same function. Improves efficiency and is easy to express and clear
  • 2. When to use the friend function:
    1) In some scenarios where operators are overloaded, youyuan is required.
    2) When two classes want to share data
  • 3. disadvantages of the youyuan method:
    1) The Enis function breaks through the encapsulation mechanism and uses the Enis function unless it is necessary.
2. youyuan relationship and object-oriented:

Next, let's talk about how to understand the relationship between friends and yuan from the object-oriented perspective. (The following content is for my personal understanding. If there is any inaccuracy, I hope I can make an ax)

  • 1) User Functions
    Youyuan functions are non-subordinate and class functions. Apart from the private variables of the class, they are similar to other functions implemented outside the class. From the object-oriented perspective, functions should not be implemented independently outside the class. Obviously, it is not an elegant solution to think independently from the perspective of object-oriented functions outside the class.
    This is related to the compatibility of C ++ with C syntax. For example, the operator <overload uses the friend function. <Function Overloading is as follows. This function is implemented independently and out of the class:

    friend ostream &operator<<(ostream &output, const object &o)

      Obviously, the <function method should be subordinate to the ostream class and implemented as a reload-able method. Definition

    Friend ostream & operator <(const object & o) // serves as a class function of ostream
    Runtime functions such as Java, Scala, and Python do not support independent functions defined with classes. From the object-oriented perspective, the subsequent language implementation is more pure. Therefore, if the code style is similar to the object-oriented style, you should try your best to implement the required functions, instead of using the functions.
    Another friend in zookeeper personally believes that, in Python, functions can be defined by directly using def, and classes are not required. Is this not in line with object-oriented logic thinking? Every function in Python is encapsulated into a function object. Therefore, everything in Python is an object and there is no function independent of the class. Like lambda expressions in Java and Scala, they are encapsulated as anonymous classes.
  • 2) youyuan class
    In the package of the youyuan class, the youyuan class changes, and all the methods in the class become the youyuan function. It seems that the above-mentioned object-oriented logic will not be broken, but there are some small pitfalls involved in inheritance. Let's take a look at it together:
    The relationship between two friends cannot be inherited. The base class's friends do not have special access permissions to the members of the derived class. If the base class is granted a friend relationship, only the base class has special access permissions. The derived class of the base class cannot access the class that grants the friend relationship.
    It's complicated to just pull the Code:

# Include <iostream> using namespace std; class A {private: int x; friend class C ;}; class B: public A {private: int y ;}; class C {voidprintA (A & a) {cout <. x <endl;} voidprintB (B & B) {cout <B. x <endl; // Class C can still access the private variables inherited from Class A from Class B using the friendly relationship. // cout <B. y <endl; Class C does not allow access to private variables of class B. If you do not inherit from these variables, the statement is invalid. }};

Obviously, the relationship between class C and A stops at the inheritance. Class C cannot implement the new private variables defined by Class B. (Here is A small question for everyone. If Class B overwrites the private variable x of Class A, can the printB in Class C still be compiled ?)

Let's look at a different piece of code:

# Include <iostream> using namespace std; class A {int x; public: friend class B ;}; class B {public: voidfun (A & a) {cout <. x <endl ;}}; class C: public B {public: // void fun2 (A & a) {cout <. a <endl;} // the newly added function of the derived class cannot access A. This sentence will return an error}; voidmain () {A; C c; c. fun (a); // C is the derived class of B. Only the fun function of the base class B can be used to access the object of}

Although Class C inherits Class B, it does not have A friend relationship with A. It can only "fight ". Dependent on the membership function inherited from Class B to sort Class. (Here we also leave a small question for you. If the fun function in Class B is protected or private, can the above Code be compiled normally ?)

Zookeeper makes a simple summary here: the relationship between friends and Yuan is not inherited among friends and can only depend on the friends and Yuan relationship of the base class.

3. How does a non-C ++ language address the relationship between friends and meta:
  • Java
    JAVA modifier type (public, protected, private)
  • Public classes, class variables and methods, any class in and out of the package can be accessed;
  • Protected classes, class variables and methods, any classes in the package, and those outside the package that inherit this class can be accessed;
  • Private classes, class variables, and methods are not accessible to any class outside the package;
  • If a class, category variable, and method are not modified with these three modifiers. Then, any class in the package can access it, and any class outside the package cannot access it (including the subclass that inherits this class outside the package ). So this type is sometimes called friendly. Now you know the source of this name. Do you have a new understanding of the classes in the same package?

  • Scala
    In Scala, private and protected can specify additional parameters. You can use private [AccessQualifier], and AccessQualifier can be this or another class name or package name. This can be understood as follows: This member is private to all classes except for the classes in the range indicated by himself and AccessQualifier. This concept can also be recursive. That is to say, if the AccessQualifier is a class, the private member is visible to the AccessQualifier.
    (This is an elegant way. I love Scala .)

  • Python
    Lao Tzu's lack of access control relies entirely on self-consciousness.
  • Golang
    The first letter is case sensitive. Fine-grained control is not feasible, but it does not seem to affect the engineering implementation in most scenarios. So is it an elegant design that turns complexity into simplicity?

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.