当我将对象传递给引用传递对象的函数时,子类被调用但是当我声明参数时,对象基类被调用。下面的例子将清楚我的疑问。
#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;
}
O / P:我是基类对象,i = 33 我是派生类对象,i = 45,j = 54
如果我宣布“void somefunc (Base obj)
”
然后输出是 O / P: 我是基类对象,i = 33 我是基类对象,i = 33
答案 0 :(得分:1)
你在1st
案例中提到的程序输出就好了。这是因为将Derived
类的对象分配给Base
类的引用是完全正确的。它没有错!对于第二种情况void somefunc (Base obj)
,如果传递Derived
的对象,将进行对象切片,因为Base
类的复制构造函数将被调用,并且它不知道{{1}的任何内容Base`将取自Derived的对象。