#include<iostream> #include<string> using namespace std; class Fruit { public: Fruit() { cout << "Buy Fruit" << endl; } void setName(string n) {name = n;} virtual void display() = 0; ~Fruit() { cout << "Eat Fruit" << endl; } protected: string name; }; class Strawberry :public Fruit { public: Strawberry() {cout << "Buy Strawberry" << endl; } void display() { cout << "Strawberry:" << name << endl; } ~Strawberry() { cout << "Eat Strawberry" << endl; } }; class Orange :public Fruit { public: Orange() { cout << "Buy Orange" << endl; } void display() { cout << "Orange:" << name << endl; } ~Orange() { cout << "Eat Orange" << endl; } }; int main() { Fruit* pa; Strawberry berry; pa = &berry; pa->setName("Milk Berry"); pa->display(); pa = new Orange; pa->setName("Sunshine"); pa->display(); delete pa; return 0; }为什么没有Eat Orange
时间: 2024-03-23 18:39:06 浏览: 14
程序中没有输出 "Eat Orange" 的原因是在 main 函数中,没有通过 delete 关键字释放 Strawberry 对象所分配的内存,而是直接结束了程序。因此,程序结束时并没有调用 Strawberry 对象的析构函数和 Orange 对象的析构函数。
在程序的末尾,应该通过 delete 关键字释放 Orange 对象所分配的内存,这样才能正确的调用 Orange 对象的析构函数,并输出 "Eat Orange"。修改后的代码如下:
```
int main() {
Fruit* pa;
Strawberry berry;
pa = &berry;
pa->setName("Milk Berry");
pa->display();
pa = new Orange;
pa->setName("Sunshine");
pa->display();
delete pa;
return 0;
}
```
这样程序就能够正确的输出 "Eat Orange",并且避免了内存泄漏的问题。
相关问题
#include<iostream> #include<cstdio> using namespace std;是什么意思
#include<iostream> #include<cstdio> using namespace std; 是C++中的预处理指令,用于引入头文件和命名空间。
1. #include<iostream> 是引入iostream头文件,其中包含了输入输出流的定义,例如cout和cin等。
2. #include<cstdio> 是引入cstdio头文件,其中包含了C语言标准输入输出函数的定义,例如printf和scanf等。
3. using namespace std; 是使用std命名空间,std是C++标准库的命名空间,其中包含了很多常用的函数和类。
这些预处理指令的作用是为了在程序中能够使用输入输出流和标准库函数,使得程序更加方便和简洁。
#include <iostream> #include <queue> #include <string> using namespace std;对代码进行注释
代码注释如下:
```c++
#include <iostream> // 引入输入输出流库
#include <queue> // 引入队列库
#include <string> // 引入字符串库
using namespace std; // 使用 std 命名空间
// 主函数
int main() {
queue<string> q; // 定义一个字符串队列 q
// 往队列中添加元素
q.push("apple");
q.push("banana");
q.push("orange");
// 输出队列头部元素
cout << q.front() << endl; // 输出:apple
// 弹出队列头部元素
q.pop();
// 输出队列头部元素
cout << q.front() << endl; // 输出:banana
// 输出队列中元素的个数
cout << "The size of the queue is " << q.size() << endl; // 输出:The size of the queue is 2
return 0; // 返回 0 表示程序正常结束
}
```