分类: C/C++
2009-07-28 10:47:59
一、 基本概念
首先,C++通过虚函数实现多态."无论发送消息的对象属于什么类,它们均发送具有同一形式的消息,对消息的处理方式可能随接手消息的对象而变"的处理方式被称为多态性。"在某个基类上建立起来的类的层次构造中,可以对任何一个派生类的对象中的同名过程进行调用,而被调用的过程提供的处理可以随其所属的类而变。"虚函数首先是一种成员函数,它可以在该类的派生类中被重新定义并被赋予另外一种处理功能。
二、 虚函数的定义与派生类中的重定义
class 类名{三、 虚函数在内存中的结构
public:
virtual 成员函数说明;
}
class 类名:基类名{
public:
virtual 成员函数说明;
}
#include "iostream.h"结果如下:Size of A = 4
#include "string.h"
class A {
public:
virtual void fun0() { cout << "A::fun0" << endl; }
};
int main(int argc, char* argv[])
{
A a;
cout << "Size of A = " << sizeof(a) << endl;
return 0;
}
class A {结果如下:Size of A = 1
public:
void fun0() { cout << "A::fun0" << endl; }
};
int main(int argc, char* argv[])
{
A a;
cout << "Size of A = " << sizeof(a) << endl;
return 0;
}
class A {结果如下:Size of A = 12
public:
virtual void fun0() { cout << "A::fun0" << endl; }
int a;
int b;
};
int main(int argc, char* argv[])
{
A a;
cout << "Size of A = " << sizeof(a) << endl;
return 0;
}
class A {结果如下:结果如下:
public:
virtual void fun0() { cout << "A::fun0" << endl; }
virtual void fun1() { cout << "A::fun1" << endl; }
int a;
int b;
};
int main(int argc, char* argv[])
{
A a;
cout << "Size of A = " << sizeof(a) << endl;
return 0;
}
class A {结果如下:Size is = 12 ,相信大家一看下面的结构图就会很清楚,
public:
virtual void f() { }
};
class B {
public:
virtual void f() { }
};
class C {
public:
virtual void f() { }
};
class Drive : public A, public B, public C {
};
int main() {
Drive d;
cout << "Size is = " << sizeof(d) << endl;
return 0;
}
class A {不用解释,相信大家一看就明白什么道理!注意:多态不是函数重载
public:
virtual void f() { cout << "A::f" << endl; }
};
class B :public A{
public:
virtual void f() { cout << "B::f" << endl;}
};
class C :public A {
public:
virtual void f() { cout << "C::f" << endl;}
};
class Drive : public C {
public:
virtual void f() { cout << "D::f" << endl;}
};
int main(int argc, char* argv[])
{
A a;
B b;
C c;
Drive d;
a.f();
b.f();
c.f();
d.f();
return 0;
}
结果:A::f
B::f
C::f
D::f
class A{在上面的例子中,如果把类A,B,C中的virtual修饰符去掉,看看打印的结果,然后再看下面一个例子想想两者的联系。如果把B和C中的virtual修饰符去掉,又会怎样,结果和没有去掉一样。
public:
virtual void f(){cout << "A::f" << endl;};
};
class B:public A{
public:
virtual void f(){cout << "B::f" << endl;};
};
class C:public A{
public:
virtual void f(){cout << "C::f" << endl;};
};
void test(A *a){
a->f();
};
int main(int argc, char* argv[])
{
B *b=new B;
C *c=new C;
char choice;
do{
cout<<"type B for class B,C for class C:"<cin>>choice;
if(choice==''b'')
test(b);
else if(choice==''c'')
test(c);
}while(1);
cout<return 0;
}
class A {打印结果:A::fun
public:
virtual void fun() {
cout << "A::fun" << endl;
}
void show() {
fun();
}
};
class B : public A {
public:
virtual void fun() {
cout << "B::fun" << endl;
}
};
int main() {
A a;
a.show();
return 0;
}
class A {
public:
void fun() {
cout << "A::fun" << endl;
}
};
class B : public A {
public:
void fun() {
cout << "B::fun" << endl;
}
void fun0() {
cout << "B::fun0" << endl;
}
};
int main() {
A *a=new A;
B *b=new B;
A *pa;
B *pb;
pb=static_cast(a); //基类指针向继承类指针进行显示转化
pb->fun0();
pb->fun();
return 0;
}