我有这段代码:
#include <iostream>
class Base {
public:
virtual void sayHello() {
std::cout << "Hello world, I am Base" << std::endl;
}
};
class Derived: public Base {
public:
void sayHello() {
std::cout << "Hello world, I am Derived" << std::endl;
}
};
void testPointer(Base *obj) {
obj->sayHello();
}
void testReference(Base &obj) {
obj.sayHello();
}
void testObject(Base obj) {
obj.sayHello();
}
int main() {
{
std::cout << "Testing with pointer argument: ";
Derived *derived = new Derived;
testPointer(derived);
}
{
std::cout << "Testing with reference argument: ";
Derived derived;
testReference(derived);
}
{
std::cout << "Testing with object argument: ";
Derived derived;
testObject(derived);
}
}
输出结果为:
Testing with pointer argument: Hello world, I am Derived
Testing with reference argument: Hello world, I am Derived
Testing with object argument: Hello world, I am Base
我的问题是为什么指针案例void testPointer(Base *obj)
和引用案例void testReference(Base &obj)
都返回void sayHello()
的派生实例的结果但是没有返回复制案例的传递?我该怎么做才能使副本案例返回派生类函数void sayHello()
的结果?
答案 0 :(得分:4)
引用引用或指针的函数引用传入的原始对象,而按值参数将创建对象的副本。因为你只是复制基础部分(因为它需要一个基础对象),你最终只使用基础部分的副本,它就像一个基础,因为它 是一个基础。 / p>
这个&#34; base-only&#34;复制被称为&#34;切片&#34;因为它只复制你的部分对象,&#34;切掉&#34;派生的部分。