boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Programming版 - 问个虚函数的作用
相关主题
C++: protect dtor
相关话题的讨论汇总
话题: print话题: virtual话题: class话题: cout话题: void
进入Programming版参与讨论
1 (共1页)
m*******o
发帖数: 264
1
Virtual methods are used for polymorphism. Consider the following three C++
classes:
class A {
public:
void print() { cout << "A"; }
}
class B : A {
public:
void print() { cout << "B"; }
}
class C : B {
public:
void print() { cout << "C"; }
}
Because print is declared as nonvirtual, the method that is invoked depends
on
the type used at compile time:
A *a = new A();
B *b = new B();
C *c = new C();
a->print(); // "A"
b->print(); // "B"
c->print(); // "C"
((B *)c)->print(); // "B
r*******y
发帖数: 290
2
because virtual function is bound at runtime
non-virtual func is bound at compilation time
in other words, virtual call is something like this:
(vptr+some address offset)->func, the vptr belongs to the actual class
non-virtual call is something like class->func, class is determined after
compilation

+

【在 m*******o 的大作中提到】
: Virtual methods are used for polymorphism. Consider the following three C++
: classes:
: class A {
: public:
: void print() { cout << "A"; }
: }
: class B : A {
: public:
: void print() { cout << "B"; }
: }

m*******o
发帖数: 264
3
Hi robustzgy, thank you for the input.
I understand what you said about the bound at runtime and compilation.
But I still can't get why in the virtual function class:
((B *)c)->print(); // out put "C", rather than B?
How do this pointer relate to the runtime or compiling time?

【在 r*******y 的大作中提到】
: because virtual function is bound at runtime
: non-virtual func is bound at compilation time
: in other words, virtual call is something like this:
: (vptr+some address offset)->func, the vptr belongs to the actual class
: non-virtual call is something like class->func, class is determined after
: compilation
:
: +

r*******y
发帖数: 290
4
no you don't understand
google virtual table and read it

【在 m*******o 的大作中提到】
: Hi robustzgy, thank you for the input.
: I understand what you said about the bound at runtime and compilation.
: But I still can't get why in the virtual function class:
: ((B *)c)->print(); // out put "C", rather than B?
: How do this pointer relate to the runtime or compiling time?

m*******o
发帖数: 264
5
哦,你这么一说我就恍然大悟了
也就是说强制转换不起作用?非virtual函数就可以强制转换?
K****n
发帖数: 5970
6
good review, thanks

【在 r*******y 的大作中提到】
: because virtual function is bound at runtime
: non-virtual func is bound at compilation time
: in other words, virtual call is something like this:
: (vptr+some address offset)->func, the vptr belongs to the actual class
: non-virtual call is something like class->func, class is determined after
: compilation
:
: +

1 (共1页)
进入Programming版参与讨论
相关主题
C++: protect dtor
相关话题的讨论汇总
话题: print话题: virtual话题: class话题: cout话题: void