gpt4 book ai didi

c++ - 在类和对象中使用 new 的指针

转载 作者:太空宇宙 更新时间:2023-11-04 13:46:32 24 4
gpt4 key购买 nike

我想知道这个指针指向的是什么鸟*对象=新猫;它是指向 Bird 类型还是 Cat 类型的对象?

class Bird
{
public:
Bird() { cout << "Bird's constructor\n"; }
void fly() { cout << "Bird's Fly\n"; }
void print() { cout << "Bird's print\n"; }
~Bird() { cout << "Bird's destructor\n"; }
};

class Cat : public Bird
{
public:
Cat() { cout << "Cat's constructor\n"; }
void fly() { cout << "cat's Fly\n"; }
void printCat() { cout << "Cat's print\n"; }
~Cat() { cout << "Cat's destructor\n"; }
};

int main()
{
Bird* object = new Cat;
return (0);
}

最佳答案

奥马尔·哈立德

回答您的问题的最佳方式是简单地运行您的代码!

正如 Igor 所提到的,变量 object 指向的是一个 Bird 基类,在 Cat 中有一个类子对象。这意味着在运行时,首先调用基类(Bird 类)的构造函数,然后调用 Cat 类的构造函数。该对象将继续继承派生类重载的函数,但不会包含派生类添加的函数。如果您运行以下代码:

int main()
{
Bird* object = new Cat;
object->fly();

return (0);
}

您将看到以下输出:

 Bird's constructor
Cat's constructor
Bird's Fly

但是,如果您运行以下代码:

int main()
{
Bird* object = new Cat;
object->fly();
object->printCat();
return (0);
}

您会注意到以下错误:

        main.cpp:27:11: error: class Bird has no member named printCat
object->printCat();
^

如有任何问题,请告诉我!

关于c++ - 在类和对象中使用 new 的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25634235/

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