【发布时间】:2021-06-27 21:14:13
【问题描述】:
#include <iostream>
#include <string>
#include <vector>
//#include "V2d.h"
using namespace std;
class item {
public:
int value;
string description;
item() {}
virtual ~item() {}
virtual void display() {
cout << "Value: " << value << endl;
}
};
class Cat : public item {
public:
string name = "Cat";
Cat() {
value = 20;
description = "a cat";
}
void display() {
cout << "Name: " << name << endl;
cout << "Value: " << value << endl;
cout << "Description: " << description << "\n" << endl;
}
};
class Dog : public item {
public:
string name = "Dog";
Dog() {
value = 10;
description = "a dog";
}
void display() {
cout << "Name: " << name << endl;
cout << "Value: " << value << endl;
cout << "Description: " << description << "\n" << endl;
}
};
class v2d {
public:
int hitPoints;
enum ItemName {
APPLE, ORANGE
};
vector<item*> inventory;
v2d() {
}
~v2d() {
for (int i = 0; i < inventory.size(); i++) {
delete inventory[i];
}
inventory.clear();
}
v2d(const v2d& orig) : inventory(orig.inventory.size()) {
hitPoints = orig.hitPoints;
for (int i = 0; i < inventory.size(); ++i) {
inventory[i] = new item(*orig.inventory[i]);
}
cout << "Copied!" << endl;
}
void display() {
for (int i = 0; i < inventory.size(); i++) {
inventory[i]->display();
}
}
};
int main() {
v2d vect1;
vect1.inventory.push_back(new Cat());
vect1.inventory.push_back(new Dog());
vect1.inventory.push_back(new Dog());
vect1.inventory.push_back(new Cat());
vect1.inventory.push_back(new Dog());
vect1.display();
cout << "**************************\n" << endl;
v2d vect2(vect1);
vect2.display();
}
我应该从哪里开始尝试重载 v2d 中的 += 和 -= 运算符以减去和添加到库存向量? 我已经完成了拥有基类和派生类的部分;我似乎在使用动态转换时遇到了麻烦不。有没有一种简单的方法可以通过复制构造函数深度复制派生类指针的向量,而不使用 clone() 函数?
【问题讨论】:
-
您可以使用每个派生类都可以覆盖的虚拟
clone方法。此外,请考虑使用智能指针而不是原始指针。 -
delete inventory[i];-- 你的item类没有虚拟析构函数。因此,如果要删除的指针是从item派生的,那么这行代码将调用未定义的行为。另外,考虑一下:v2d vect1; Dog d; vect1.inventory.push_back(&d);——这也会调用未定义的行为,因为d没有分配给new。
标签: c++ pointers containers