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

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值