#include<iostream>
using namespace std;
class A
{
public:
A(int a=0)
{
this->a = a;
cout << "我是爸爸构造"<< endl;
}
void virtual printf()
{
cout << "我是爸爸 a="<<a<< endl;
}
private:
int a;
};
class B :public A
{
public:
B(int b = 0) :A(0)
{
this->b = b;
cout <<"我是儿子构造函数" << endl;
}
void printf()
{
cout << "我是儿子 b="<<b<< endl;
}
private:
int b;
};
//在父类同名函数钱加上 virtual后,一种调用语句会实现多种表现形态
void howprintf(A *p)
{
p->printf();
}
void howprintf1(A &p)
{
p.printf();
}
//当在子类父类同名函数前加上virtual前,输出结果均为父类的printf
//但是在父类同名函数钱加上 virtual后,输出我们想要的结果
void main()
{
A *p = NULL;
A a1;
B b1;
p = &a1;
p->printf();
p = &b1;
p->printf();
howprintf(&a1);
howprintf(&b1);
howprintf1(a1);
howprintf1(b1);
system("pause");
}