C++中的对象切片

在C++中,派生类对象可以被分配给基类对象,但另一种方式是不可能的。

null

C++

class Base { int x, y; };
class Derived : public Base { int z, w; };
int main()
{
Derived d;
Base b = d; // Object Slicing,  z and w of d are sliced off
}


对象切片 当派生类对象被指定给基类对象时,派生类对象的附加属性被切掉以形成基类对象。

C++

#include <iostream>
using namespace std;
class Base
{
protected :
int i;
public :
Base( int a)     { i = a; }
virtual void display()
{ cout << "I am Base class object, i = " << i << endl; }
};
class Derived : public Base
{
int j;
public :
Derived( int a, int b) : Base(a) { j = b; }
virtual void display()
{ cout << "I am Derived class object, i = "
<< i << ", j = " << j << endl;  }
};
// Global method, Base class object is passed by value
void somefunc (Base obj)
{
obj.display();
}
int main()
{
Base b(33);
Derived d(45, 54);
somefunc(b);
somefunc(d); // Object Slicing, the member j of d is sliced off
return 0;
}


输出:

I am Base class object, i = 33I am Base class object, i = 45

通过使用指针或引用,我们可以避免上述意外行为。当对象的指针或引用作为函数参数传递时,不会发生对象切片,因为任何类型的指针或引用占用相同的内存量。例如,如果我们将上述程序中的全局方法myfunc()更改为following,则不会进行对象切片。

C++

// rest of code is similar to above
void somefunc (Base &obj)
{
obj.display();
}
// rest of code is similar to above


输出:

I am Base class object, i = 33I am Derived class object, i = 45, j = 54

如果我们使用指针并将程序更改为following,我们会得到相同的输出。

C++

// rest of code is similar to above
void somefunc (Base *objp)
{
objp->display();
}
int main()
{
Base *bp = new Base(33) ;
Derived *dp = new Derived(45, 54);
somefunc(bp);
somefunc(dp); // No Object Slicing
return 0;
}


输出:

I am Base class object, i = 33I am Derived class object, i = 45, j = 54

通过禁止对象创建,使基类函数完全虚拟,可以防止对象切片。不可能创建包含纯虚方法的类的对象。 本文由 普拉瓦西会面 。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请发表评论

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享