2008 March 29th Saturday (三月 二十九日 土曜日)

来源:互联网 发布:跳过广告的软件 编辑:程序博客网 时间:2024/04/30 09:46
#include <iostream>

  The "virtual" key in C++ means from a base class, which might has parents, to its dervied classes, the "virtual" functions can be
inherited in interface and implement modes.  It means its children can custom a virtual function's behavior as their wishes.  Of course,
if a pure virtual function, children have to implement the interface.

using namespace std;

class A{
public:
void say(){
cout<<"A"<<endl;
}
};

class B: public A{
public:
virtual void say(){
cout<<"B"<<endl;
}
};

class C: public B{
public:
virtual void say(){
cout<<"C"<<endl;
}
};

int main(){
A a;
B b;
C c;

A *pa = &b;
pa->say();     // -> A

B *pb = &b;
pb->say();     // -> B

B *pc = &c;
pc->say();     // -> C

return 0;
}

  As for non-virtual functions, it means that children inherit those function from parents and have better not modify those behaviors.
That likes the "final" key for a member in Java, but it isn't restricted at compilation time.

  After you redefined a non-virtual member from parent class, invoking them, which member is called according to it belong to which class
object of a pointer pointed which class object.  There is not dynamic virtual function table.

using namespace std;

class A{
public:
void say(){
cout<<"A"<<endl;
}
};

class B: public A{
public:
void say(){
cout<<"B"<<endl;
}
};

int main(){
A a;
B b;

A *pa = &b;
pa->say();     // -> A

B *pb = &b;
pb->say();     // -> B

return 0;
}

原创粉丝点击