一道非常基础的题目,请回复下面程序的结果:
#include <iostream.h>
class ClassA
{
public:
void fun1();
void fun2();
virtual void fun3();
};
void ClassA::fun1()
{
cout << "ClassA.fun1"<<endl;
};
void ClassA::fun2()
{
cout << "ClassA.fun2"<<endl;
};
void ClassA::fun3()
{
cout << "ClassA.fun3"<<endl;
};
class ClassB : public ClassA
{
public:
void fun1();
void fun2();
virtual void fun3();
};
void ClassB::fun3()
{
cout << "ClassB.fun3"<<endl;
};
class ClassC : public ClassB
{
public:
void fun1();
void fun2();
virtual void fun3();
};
void ClassC::fun3()
{
cout << "ClassC.fun3"<<endl;
};
void main()
{
ClassA *a[3];
ClassA a1;
ClassB b1;
ClassC c1;
a1.fun3();
b1.fun3();
c1.fun3();
a[0] = &a1;
a[1] = &b1;
a[2] = &c1;
cout << "virtual function array test" <<endl;
for(int i=0;i<3;i++)
{
a[i]->fun3();
}
cout << "((ClassA)&b1).fun3():";
((ClassA*)&b1)->fun3();
//object slicing
cout << "object slicing"<<endl;
cout <<"((ClassA)b1).fun3():";
((ClassA)b1).fun3();
}
class ClassA
{
public:
void fun1();
void fun2();
virtual void fun3();
};
void ClassA::fun1()
{
cout << "ClassA.fun1"<<endl;
};
void ClassA::fun2()
{
cout << "ClassA.fun2"<<endl;
};
void ClassA::fun3()
{
cout << "ClassA.fun3"<<endl;
};
class ClassB : public ClassA
{
public:
void fun1();
void fun2();
virtual void fun3();
};
void ClassB::fun3()
{
cout << "ClassB.fun3"<<endl;
};
class ClassC : public ClassB
{
public:
void fun1();
void fun2();
virtual void fun3();
};
void ClassC::fun3()
{
cout << "ClassC.fun3"<<endl;
};
void main()
{
ClassA *a[3];
ClassA a1;
ClassB b1;
ClassC c1;
a1.fun3();
b1.fun3();
c1.fun3();
a[0] = &a1;
a[1] = &b1;
a[2] = &c1;
cout << "virtual function array test" <<endl;
for(int i=0;i<3;i++)
{
a[i]->fun3();
}
cout << "((ClassA)&b1).fun3():";
((ClassA*)&b1)->fun3();
//object slicing
cout << "object slicing"<<endl;
cout <<"((ClassA)b1).fun3():";
((ClassA)b1).fun3();
}
如果你知道结果,请回复!以后我再解释virtual function是怎么实现多态的!