通过引用传递是否总是可以避免切片问题?

2024-02-22

这让我有点惊讶,但我正在研究一些代码,发现至少在我的计算机上,当函数通过引用接受父类并且传递子实例时,不会发生切片问题。为了显示:

#include <iostream>

class Parent
{
public:
    virtual void doSomething()
    {
        using namespace std;
        cout << "Parent::DoSomething" << endl;
    }
};

class Child : public Parent
{
public:
    virtual void doSomething()
    {
        using namespace std;
        cout << "Child::DoSomething" << endl;
    }
};

void performSomething(Parent& parent)
{
    parent.doSomething();
}

int main(int argc, char** argv)
{
    Child myChild;

    performSomething(myChild);

    return 0;
}

这打印出来Child::DoSomething.

就像我说的,我有点惊讶。我的意思是,我知道通过引用传递是like传递指针(但在我的理解中更安全),但我不知道这样做时我仍然需要保持多态性。

我只是想确定,这是应该发生的还是“它在我的机器上运行”类型的实例之一?


“切片”是指基复制构造函数无法区分派生类的精确类型匹配。调用切片的唯一方法是调用基本复制构造函数。通常,当按值传递参数时会发生这种情况,但也可以设计其他情况:

class Base { };
class Derived : public Base { };

void foo(Base);

int main()
{
  Derived x;

  Base y = x;   // flagrant slicing
  foo(x);       // slicing by passing by value
}

你从来没有做过任何这样的事情,所以你不会遇到任何切片的情况。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过引用传递是否总是可以避免切片问题? 的相关文章

随机推荐