C++ 对象模型 ch1 关于对象

本文探讨了C++中通过派生类对象初始化基类对象时发生的数据“切片”现象,并展示了如何影响虚函数的调用。通过具体的代码示例,解释了在不同上下文中调用虚函数时的行为差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值