通过引用传递总是避免切片问题? [英] Does passing by reference always avoid the slicing issue?

查看:173
本文介绍了通过引用传递总是避免切片问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这让我吃惊了一点,但我玩了一些代码,发现,至少在我的电脑上,当一个函数接受一个父类通过引用和你传递一个子实例,切片问题不会发生。说明:

This surprised me a little bit, but I was playing around with some code and found out that, at least on my computer, when a function accepts a parent class by reference and you pass a child instance, that the slicing problem doesn't occur. To illustrate:

#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 I said, I was a little surprised. I mean, I know that passing by reference is like passing pointers around (but much safer in my understanding), but I didn't know I still got to keep polymorphic goodness when doing so.

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

I just want to make sure, is this supposed to happen or is it one of those "it works on my machine" type of instances?

推荐答案

您看到的行为是正确的。这是它应该如何工作。引用的工作方式与指针类似。

The behavior you are seeing is correct. This is how it is supposed to work. References work just like pointers.

这篇关于通过引用传递总是避免切片问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆