1. demo
#include <iostream> using namespace std; class X { public: int a; virtual void foo() { cout << " I am in X " << endl; } }; class Y : public X { public: void foo() { cout << " I am in Y " << endl; } }; void f(X x, X* x1, X& x2) { x.foo(); x1->foo(); x2.foo(); } int main() { X x; X* x1 = new Y(); cout << sizeof(x1) << endl; X& x2 = *x1; f(*x1, x1, x2); }2. 输出:
/home/a/j/nomad2:uname -a
FreeBSD freebsd.unix-center.net 7.2-RELEASE-p8 FreeBSD 7.2-RELEASE-p8 #0: Tue May 25 17:51:43 UTC 2010 root@amd64-builder.daemonology.net:/usr/obj/usr/src/sys/GENERIC amd64
/home/a/j/nomad2:./a.out
8
I am in X
I am in Y
I am in Y
3. 关于第一个调用输出X,解释如下:
When a base class object is directly initialized or assigned with a derived class object, the derived object is sliced to fit into the available memory resources of the base type. There is nothing of the derived type remaining. Polymorphism is not present, and an observant compiler can resolve an invocation of a virtual function through the object at compile time, thus by-passing the virtual mechanism. This can be a significant performance win if the virtual function is defined as inline.
本文探讨了C++中通过派生类对象初始化基类对象时发生的数据“切片”现象,并展示了如何影响虚函数的调用。通过具体的代码示例,解释了在不同上下文中调用虚函数时的行为差异。
820

被折叠的 条评论
为什么被折叠?



