//Source filename: Win32Con.cpp
#include <iostream>
using namespace std;
class parent1
{
public:
virtual int fun1(){
cout<<"parent1::fun1()"<<endl;return 0;
};
virtual int fun2()=0;
};
class child1:public parent1
{
public:
virtual int fun1()
{
cout<<"child1::fun1()"<<endl;
parent1::fun1();
return 0;
}
virtual int fun2()
{
cout<<"child1::fun2()"<<endl;
return 0;
}
};
class grandson:public child1
{
public:
virtual int fun2()
{
cout<<"grandson::fun2()"<<endl;
//parent1::fun2();
parent1::fun1();
child1::fun2();
return 0;
}
};
void test_func1(parent1 *pp)
{
pp->fun1();
pp->fun2();
}
int main(int argc, char* argv[])
{
grandson sunzi;
test_func1(&sunzi);
return 0;
}
#include <iostream>
using namespace std;
class parent1
{
public:
virtual int fun1(){
cout<<"parent1::fun1()"<<endl;return 0;
};
virtual int fun2()=0;
};
class child1:public parent1
{
public:
virtual int fun1()
{
cout<<"child1::fun1()"<<endl;
parent1::fun1();
return 0;
}
virtual int fun2()
{
cout<<"child1::fun2()"<<endl;
return 0;
}
};
class grandson:public child1
{
public:
virtual int fun2()
{
cout<<"grandson::fun2()"<<endl;
//parent1::fun2();
parent1::fun1();
child1::fun2();
return 0;
}
};
void test_func1(parent1 *pp)
{
pp->fun1();
pp->fun2();
}
int main(int argc, char* argv[])
{
grandson sunzi;
test_func1(&sunzi);
return 0;
}
本文通过一个具体的 C++ 示例介绍了类继承与多态的概念。演示了基类与派生类之间的关系,以及如何在派生类中重写基类的方法。此外,还展示了如何使用指向基类的指针来调用派生类的方法,以此实现运行时多态。
583

被折叠的 条评论
为什么被折叠?



