#include"iostream.h"
class Base
{
public:
Base(int i):a(i){}
virtual void fun()
{
cout << "Base's funciton" <<endl;
}
void this_fun(Base *b)
{
if (b == this)
cout << "It is Base's this" <<endl;
}
public:
int a0;
private:
int a;
};
class Derived: public Base
{
public:
Derived(int i):Base(i+1),d(i){}
virtual void fun()
{
cout << "Derived's function" <<endl;
}
void this_fun(Derived *d)
{
if (d == this)
cout << "It is Derived's this" <<endl;
}
public:
int d0;
private:
int d;
};
class Other
{
public:
Other();
void fun()
{
cout << "Other's funciton" <<endl;
}
void this_fun(Other *o)
{
if (o == this)
cout << "It is Other's this" <<endl;
}
public:
int o;
};
int main()
{
cout<<"第一類測驗(父->子):"<<endl;
Base b1(1);
Derived *d1=(Derived*) &b1; //將父類物件的指標強制型別轉換為子類指標,并賦給一個子類指標
d1->this_fun(d1);
d1->fun();
cout<<endl<<endl;
cout<<"第二類測驗(子->父):"<<endl;
Derived d2(1);
Base *b2=(Base*) &d2; //將子類物件的指標強制型別轉換為父類指標,并賦給一個父類指標
b2->this_fun(b2);
b2->fun();
cout<<endl<<endl;
cout<<"第三類測驗:"<<endl;
Base *b3=new Base(1);
Other *o=(Other*)b3;//將Base類物件的指標強制型別轉換為Other類指標,并賦給一個Other類指標
cout<<"*b3="<<b3<<endl;
cout<<"*o="<<o<<endl;
cout<<endl;
b3->this_fun(b3);
b3->fun();
cout<<endl;
o->this_fun(o);
o->fun();
cout<<endl<<endl;
return 0;
}
uj5u.com熱心網友回復:
C++中本來就應該禁止使用C的強轉,應該根據情況使用相應的轉換運算子。父類 -> 到子類,需使用dynamic_cast,強轉后果未知
子類->父類 無需強轉,物件還是子類,呼叫的虛函式自然是子類的方法,非虛則是父類方法。
Base->Other 強轉后果未知,應該用static_cast才行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/81043.html
標籤:基礎類
