gpt4 book ai didi

c++ - 将派生类传递给基类参数的函数

转载 作者:太空狗 更新时间:2023-10-29 20:20:50 61 4
gpt4 key购买 nike

我有这个代码:

#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) 都返回 的派生实例的结果code>void sayHello() 但不是复制情况?应该怎么做才能让copy case返回派生类函数void sayHello()的结果?

最佳答案

采用引用或指针的函数引用传入的原始对象,而按值参数将创建对象的拷贝。由于您只是复制基础部分(因为它需要一个基础对象),所以您最终只使用基础部分的拷贝,它就像一个基础部分,因为它一个基础。

这种“仅基”复制称为“切片”,因为它只复制对象的一部分,“切掉”派生部分。

关于c++ - 将派生类传递给基类参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47880365/

61 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com