gpt4 book ai didi

c++ - 要求澄清将类实例放入数组和使用虚拟方法

转载 作者:行者123 更新时间:2023-11-28 04:19:45 25 4
gpt4 key购买 nike

<分区>

注意:我不同意这是链接问题的重复。虽然这是一个问题,但这不是问题。请看下面。

当我将一个新的类实例分配给一个数组时,基类的虚函数用于代替重写的派生类虚函数。

有人告诉我下面代码的问题是 object slicing .然而,根据this YouTube video ,这应该有效。我是 C++ 的初学者,所以我不确定谁是对的。有人可以指出我正确的方向或告诉我哪里出了问题吗?

这是因为我将对象复制到数组而不是“指向”它吗?但是,我不知道如何正确执行此操作。

请参阅下面的代码了解我的尝试。

附录:这里实际上存在一个对象切片问题。但是,我的问题的目的和我不理解的是,重写仅在您使用指针或指针数组时有效,而不是在您声明实例数组时有效。

#include <iostream>

// I know these should be structs since they're all public!
class Animal {
public:
Animal() { std::cout << "Animal constructor\n"; }
virtual void speak() { std::cout << "Animal/Hello!\n"; }
};

class Dog: public Animal {
public:
Dog() { std::cout << "Dog constructor\n"; }
void speak() override { std::cout << "Dog/Bark!\n"; }
};

int main() {
const int Size = 4;

Animal* Kingdom = new Animal[Size];
Dog* rover = new Dog;

// Legal because of polymorphism:
Animal* spot = new Dog;

// Legal because of polymorphism;
// Believe this is wrong - I think I'm copying the value rather than
// pointing to it, but not sure what the right way is...
Kingdom[0] = *(new Dog);
// &Kingdom[0] = new Dog; // Error - left operand must be l-value
// Kingdom = new Dog; // Wrong - changing array base, leaking memory

Kingdom[1] = *rover;
Kingdom[2] = *spot;

// Virtual method followed here:
std::cout << "\nIndividual invocations:\n";
rover->speak();
spot->speak();

std::cout << "\nInvocation from array:\n";
for (int i = 0; i < Size; ++i)
// Doesn't work - virtual method not followed, not sure why...
// Kingdom[i].speak();
// No difference between these two forms:
(Kingdom + i)->speak();

// PS - I know I should put deletes in here not to leak memory!
}

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