#include <iostream>
using namespace std;
class parent{
public:
parent(int a)
{
this->va = a;
}
virtual void print(void)
{
cout << "基类的a" <<this->va<< endl;
}
private:
int va;
};
class child : public parent{
public:
child(int a) : parent(100)
{
this->a = a;
}
virtual void print(void)
{
cout << "派生类的a" <<this->a<< endl;
}
private:
int a;
};
int main()
{
child oop(10);
parent oop1(20);
parent* p = NULL;
p = &oop;
p = &oop1;
parent &pt = oop;
p->print();
pt.print();
system("pause");
return 0;
}
* 父类指针可以直接指向子类对象
* 父类引用可以直接指向子类对象
上述结论不管是父类指针还是引用指向子类对像,调用的print都是父类的print,这种解决办法是在print的实现前面加上virtual关键字
实例:
#include <iostream>
using namespace std;
class parent{
public:
parent(int a)
{
this->va = a;
}
virtual void print(void)
{
cout << "基类的a" <<this->va<< endl;
}
private:
int va;
};
class child : public parent{
public:
child(int a) : parent(100)
{
this->a = a;
}
virtual void print(void)
{
cout << "派生类的a" <<this->a<< endl;
}
private:
int a;
};
void test1(parent* p)
{
p->print();
}
void test2(parent & pt)
{
pt.print();
}
int main()
{
child oop(10);
parent oop1(20);
parent* p = NULL;
p = &oop;
p = &oop1;
parent &pt = oop;
p->print();
pt.print();
test1(&oop);
test1(&oop1);
test2(oop);
test2(oop1);
system("pause");
return 0;
}
这样就可执行到子类的print了,这里的virtual也可以只加载父类的virtual前,这也是一种多态的调用案例