Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the C++ private inheritance method?

Shulou Source: shulou.com Published: 2022-06-01 23:48:45 10月03日 Update

This article introduces the knowledge of "what is the private inheritance method of C++". In the operation of practical cases, many people will encounter such a dilemma. Then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Access base class methods

We know that in private inheritance, the public object of the base class and the protected object become the private object of the derived class. We can use it in derived class methods, but we cannot call it directly through derived class objects, but we cannot access the private methods and objects of the base class.

This concept is easy for us to understand, but when it comes to implementation, how do we call the public or protected methods of the base class in the methods of the derived class?

For example, in the previous class declaration, we declared an Average method to calculate the average score of the student's test score. Since the Student class inherits the valarray class rather than contains an instance of valarray, how do we call the public method of valarray in the implementation of the Average method?

The answer is to call by parsing operators and class names

Double Student::Average () const {if (ArrayDb::size () > 0) {return ArrayDb::sum () / ArrayDb::size ();} return 0;} 2. Access the base class object

Now we know that we can access the base class's methods using the parsing operator, but the question is, what should we do if we no longer want to access the base class's method but the base class object itself?

For example, in the same example, we have a Name method that needs to return the student's name. Since the Student class only inherits the string class and does not have its own string instance, we need to return the base class object itself.

Again, how do we do it?

The answer is to use a cast.

Const string& Student::Name () const {return (const string&) * this;}

Because the Student class is derived from the string class, we can cast the Student object into a string object.

3. Access the friends of the base class

Methods and objects are easy to handle, but what about friends? Because the friend function does not belong to the class, it cannot be done through the class name or the parsing operator. In this case, we can only do it by explicitly converting the derived class.

For example:

Ostream & operator

Tags: Method object type private case clocked instance answer operator force operation content function student what to do pointer more knowledge class name question Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Shulou Tech Info Apple MariaDB Huawei