1 显示效果
2 代码
#include "Windows.h"
#include "iostream"
using namespace std;
class PayInterface //定义支付接口基类
{
public:
PayInterface() //该类虽然不能被实例化,但是它的子类实例化时,也会调用它的构造函数
{
cout << "支付接口构造函数!" << endl;
}
virtual void pay() = 0; //纯虚函数
};
class Pay : public PayInterface //支付类
{
public:
static Pay * PayPoint;
Pay()
{
PayPoint = this; //子类的指针赋值给父类
cout << "支付类的构造函数" << endl;
}
~Pay()
{
cout << "支付类的析构函数" << endl;
}
static Pay * GetInstancePoint() //静态成员函数
{
if(PayPoint != NULL)
return PayPoint;
}
virtual void pay() =0; //纯虚函数
};
Pay * Pay::PayPoint = NULL;
class WeiXinPay : public Pay//微信支付类
{
public:
WeiXinPay()
{
cout << "微信支付类构造函数" << endl;
}
~WeiXinPay()
{
cout << "微信支付类析构函数" << endl;
}
virtual void pay()
{
cout <<"调用微信支付接口"<< endl;
}
};
class AliPay : public Pay//支付宝支付类
{
public:
AliPay()
{
cout << "调用支付宝支付类的构造函数" << endl;
}
~AliPay()
{
cout << "调用支付宝支付类的析构函数" << endl;
}
void pay()//override父类纯虚函数
{
cout << "调用支付宝接口" << endl;
}
};
void main()
{
//Pay pay; 该语句是错误的:因为Pay类中有纯虚函数,因此不能实例化
WeiXinPay WxPay;
Pay::GetInstancePoint()->pay(); //多态 调用微信的支付接口
cout << "-------------" << endl;
AliPay APay;
Pay::GetInstancePoint()->pay();//多态 调用
system("pause");
}