这让我感到有点惊讶,但是我正在玩弄一些代码,发现至少在我的电脑上,当函数通过引用接受父类并传递子实例时,切片问题不会'发生。举例说明:通过引用传递总是避免切片问题?
#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
。
就像我说的,我有点惊讶。我的意思是,我知道通过引用传递就像传递指针(但我的理解更安全),但我不知道在这样做时我仍然要保持多态。
我只是想确认一下,这是否应该发生,或者它是那些“它适用于我的机器”类型的实例?
这不是什么“切片”。此外,该代码甚至编译?什么是'使用std;'? –
表示它是'使用命名空间std'。我想我能够明白这一点,但是清理了代码,以使整个网站受益。 – Anthony