注册 登录
编程论坛 C++教室

[求助]对象切片问题

sbivfh 发布于 2007-07-04 13:07, 628 次点击
#include<iostream>
class A
{
public:
/*virtual*/ void print();

};
class B:public A
{
public:
void print();
};
void A::print()
{
std::cout<<"Test the slice_up question!---A"<<std::endl;
}
void B::print()
{
std::cout<<"Test the slice_up question!---B"<<std::endl;
}
int main()
{ A aa;
B bb;
A *pbb;
pbb=&bb;

A *paa;
paa=&aa;
paa->print();
pbb->print();
//////////////////////////////////////////////////会发生切片现象
B b;
A a=b;
a.print();
b.print();
/////////////////////////////////////////////////不会发生切片现象

B *pb=new B;
A* pa=pb;
a.print();
b.print();
system("pause");
return 0;
}

请问:对象切片现象有什么后果?也就是切片现象主要表现在哪个方面?上面是自己随便写的,没测试出来,可能是没写出来吧。应该如何测试啊,谢谢!
3 回复
#2
HJin2007-07-04 13:26
Object slicing happens when you upcast an object to its base class. The effect will be that you lose the specific "derived parts" of the obj.
#3
sbivfh2007-07-04 13:34

Thank you!

#4
sbivfh2007-07-04 13:44
HJin:
Could you give me an example.
1