Home > Back-end >  About two unrelated classes pointer casting, why each pointer or call the respective function
About two unrelated classes pointer casting, why each pointer or call the respective function

Time:09-26

# include "iostream. H"

The class Base
{
Public:
The Base (int I) : a (I) {}
Virtual void fun ()
{
Cout & lt; & lt; "Base 's funciton" & lt; & lt; Endl;
}
Void this_fun (Base * b)
{
If (b==this)
Cout & lt; & lt; "It is the Base 's this" & lt; & lt; Endl;
}

Public:
Int a0;

Private:
Int a;

};

The class Derived: public Base
{
Public:
Derived (int I) : the Base (I + 1), d (I) {}
Virtual void fun ()
{
Cout & lt; & lt; "Derived 's function & lt;" & lt; Endl;
}

Void this_fun (Derived * d)
{
If (d==this)
Cout & lt; & lt; "It is Derived 's this" & lt; & lt; Endl;
}

Public:
Int d0;

Private:
Int d;

};

The class Other
{
Public:
Other ();

Void fun ()
{
Cout & lt; & lt; "The Other 's funciton" & lt; & lt; Endl;
}
Void this_fun * o (Other)
{
If (o==this)
Cout & lt; & lt; "It is Other 's this" & lt; & lt; Endl;
}

Public:
Int o;

};

Int main ()
{
cout<" The first test (parent - & gt; Son: "& lt; & lt; Endl;
Base b1 (1);
Derived * d1=(Derived *) & amp; B1.//superclass object pointer casts into subclasses pointer, and assigned to a pointer to a subclass
D1 - & gt; This_fun (d1);
D1 - & gt; Fun ();
cout<& lt; Endl<& lt; Endl;



cout<" The second type of test (a - & gt; The father) : "& lt; & lt; Endl;
Derived d2 (1);
The Base * b2=(Base *) & amp; D2.//subclass object pointer casting as the pointer to the parent class, and is assigned to a pointer to the parent class
B2 - & gt; This_fun (b2);
B2 - & gt; Fun ();
cout<& lt; Endl<& lt; Endl;



cout<" The third type of test: "& lt; & lt; Endl;
The Base * b3=new Base (1);
Other * o=b3 (Other *);//the Base class object pointer casts for Other kind of pointer, and assigned to a pointer to an Other kind of

cout<" * b3="& lt; & lt; B3 & lt; & lt; Endl;
cout<" * o="& lt; & lt; O<& lt; Endl;
cout<& lt; Endl;

B3 - & gt; This_fun (b3);
B3 - & gt; Fun ();
cout<& lt; Endl;
O - & gt; This_fun (o);
O - & gt; Fun ();
cout<& lt; Endl<& lt; Endl;


return 0;
}

CodePudding user response:

C + + was always supposed to ban the use of C is strong, should according to the situation with the corresponding conversion operators,

The parent class - & gt; Turn to the subclass, need to use dynamic_cast, strong unknown consequences
The subclass - & gt; Parent without strong turn, objects, or a subclass, call the virtual function of nature is a subclass of method, the virtual is the parent class method,
Base - & gt; Other strong turn unknown consequences, should use the static_cast,
  • Related