#include <iostream>
using namespace std;
/* 每个类都有一张虚方法表,当基类为虚方法,而派生类重载了虚方法,
* 则虚方法表中的基类方法被派生类替换
*/
class AClass{
public:
AClass(){
cout << this << " 基类构造" << endl;
}
virtual ~AClass(){
cout << this << " 基类析构" << endl;
}
void Amothod1(){
cout << "基类方法1" << endl;}
virtual void Amothod2(){
cout << "基类方法2" << endl;}
void Amothod3(){
cout << "基类方法3" << endl;}
};
class BClass:public AClass{
public:
BClass(){
cout << this << " 派生类构造" << endl;
}
virtual ~BClass(){
cout << this << " 派生类析构" << endl;
}
void Amothod1(){
cout << "派生类方法1" << endl;}
void Amothod2(){
cout << "派生类方法2" << endl;}
};
int main()
{
AClass * a = new AClass;// 基类指针操纵基类实例
a->Amothod1();// 调用基类方法1
a->Amothod2();// 调用基类方法2
a->Amothod3();// 调用基类方法3
delete a;
cout << "***虚方法不影响指向基类实例的基类指针***" << endl;
AClass * a1 = new BClass;// 基类指针操纵派生类实例
a1->Amothod1();// 调用基类方法1
a1->Amothod2();// 调用派生类方法2
a1->Amothod3();// 调用基类方法3
// ((BClass *)a1)->Amothod1();// 等效于b->Amothod1();
// ((BClass *)a1)->Amothod2();// 等效于b->Amothod2();
// ((BClass *)a1)->Amothod3();// 等效于b->Amothod3();
delete a1;
cout << "***虚方法影响指向派生类实例基类指针***" << endl;
BClass * b = new BClass;// 派生类指针操纵派生类实例
b->Amothod1();// 调用派生类方法1
b->Amothod2();// 调用派生类方法2
b->Amothod3();// 调用基类方法3
// ((AClass *)b)->Amothod1();// 等效于a1->Amothod1();
// ((AClass *)b)->Amothod2();// 等效于a1->Amothod2();
// ((AClass *)b)->Amothod3();// 等效于a1->Amothod3();
delete b;
cout << "***如果不重载基类公共方法,将直接调用基类方法***" << endl;
return 0;
}
using namespace std;
/* 每个类都有一张虚方法表,当基类为虚方法,而派生类重载了虚方法,
* 则虚方法表中的基类方法被派生类替换
*/
class AClass{
public:
AClass(){
cout << this << " 基类构造" << endl;
}
virtual ~AClass(){
cout << this << " 基类析构" << endl;
}
void Amothod1(){
cout << "基类方法1" << endl;}
virtual void Amothod2(){
cout << "基类方法2" << endl;}
void Amothod3(){
cout << "基类方法3" << endl;}
};
class BClass:public AClass{
public:
BClass(){
cout << this << " 派生类构造" << endl;
}
virtual ~BClass(){
cout << this << " 派生类析构" << endl;
}
void Amothod1(){
cout << "派生类方法1" << endl;}
void Amothod2(){
cout << "派生类方法2" << endl;}
};
int main()
{
AClass * a = new AClass;// 基类指针操纵基类实例
a->Amothod1();// 调用基类方法1
a->Amothod2();// 调用基类方法2
a->Amothod3();// 调用基类方法3
delete a;
cout << "***虚方法不影响指向基类实例的基类指针***" << endl;
AClass * a1 = new BClass;// 基类指针操纵派生类实例
a1->Amothod1();// 调用基类方法1
a1->Amothod2();// 调用派生类方法2
a1->Amothod3();// 调用基类方法3
// ((BClass *)a1)->Amothod1();// 等效于b->Amothod1();
// ((BClass *)a1)->Amothod2();// 等效于b->Amothod2();
// ((BClass *)a1)->Amothod3();// 等效于b->Amothod3();
delete a1;
cout << "***虚方法影响指向派生类实例基类指针***" << endl;
BClass * b = new BClass;// 派生类指针操纵派生类实例
b->Amothod1();// 调用派生类方法1
b->Amothod2();// 调用派生类方法2
b->Amothod3();// 调用基类方法3
// ((AClass *)b)->Amothod1();// 等效于a1->Amothod1();
// ((AClass *)b)->Amothod2();// 等效于a1->Amothod2();
// ((AClass *)b)->Amothod3();// 等效于a1->Amothod3();
delete b;
cout << "***如果不重载基类公共方法,将直接调用基类方法***" << endl;
return 0;
}