C++: related knowledge points of classes 1

this pointer

If you want to explicitly refer to the object used in the member function , you can use the predefined pointer this.
eg:

struct Date{
    int d,m,y;
    int month() const {return this->m; 
}

friend function

We can grant independent functions access to all class members through a friend declaration.
A friend function of a class is defined outside the class, but has access to all private and protected members of the class. Although the prototype of a friend function appears in the class definition, a friend function is not a member function.

A friend can be a function, which is called a friend function; a friend can also be a class, which is called a friend class, in which case the entire class and all its members are friends.

#include <iostream>

using namespace std;

class Box
{
   double width;
public:
   friend void printWidth( Box box );
   void setWidth( double wid );
};

// 成员函数定义
void Box::setWidth( double wid )
{
    width = wid;
}

// 请注意:printWidth() 不是任何类的成员函数
void printWidth( Box box )
{
   /* 因为 printWidth() 是 Box 的友元,它可以直接访问该类的任何成员 */
   cout << "Width of box : " << box.width <<endl;
}

// 程序的主函数
int main( )
{
   Box box;

   // 使用成员函数设置宽度
   box.setWidth(10.0);

   // 使用友元函数输出宽度
   printWidth( box );

   return 0;
}

When the above code is compiled and executed, it produces the following results:

Width of box : 10

C++ friend functions

Derived class

A class can be defined as a derived class of other classes, it inherits the members of the class from which it is derived (the base class).
Like members, bases can also be public or private

class DD: public B1, private B2{
    //....
}

In this way, the public members of B1 become public members of DD, and the public members of B2 become private members of DD.
The derived class has no special access rights to the members of the base class, so DD cannot access the private members of B1 or B2.
The above inheritance method is called multiple inheritance . It should be noted that there is no multiple inheritance in C#.
A pointer to D can be implicitly converted to a pointer to B as long as the base class B is accessible and unambiguous in the derived class D.

struct B {};
struct B1 : B {};//B是B1的一个公有基类
struct B2 : B {};//B是B2的一个公有基类
struct C {};
struct DD : B1, B2, private C {};

DD* p = new DD;
B1* pd1 = p;//正确
B* pb = p;//错误,出现二义性:B1::B还是B2::B?
C* pc = p;//错误,DD::C是私有的

Guess you like

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