【发布时间】:2016-11-16 10:30:28
【问题描述】:
我有一个 Animal 类,它是几个不同 Animals 的基类,还有一个 Herd 类,它将 shared_prt 存储在一个向量中的动物身上。我不熟悉智能指针,但我不得不在我的代码中使用它们来处理继承。它似乎工作正常,但在我的代码到达“Herd”的析构函数后,它会抛出一个error。 它有什么问题?
class Animal {
public:
Animal(string _sound) :
sound(_sound) {}
void give_sound() {
cout << sound << " ";
}
bool operator==(Animal arg) {
return (typeid(*this).name() == typeid(arg).name());
}
protected:
string sound;
};
class Dog : public Animal {
public:
Dog() : Animal("woof") {}
};
class Cat : public Animal {
public:
Cat() : Animal("meow") {}
};
class Cow : public Animal {
public:
Cow() : Animal("moo") {}
};
class Herd {
public:
Herd() {}
~Herd() {
vec.clear();
}
Herd operator+(Animal *arg) {
shared_ptr<Animal> ptr(arg);
vec.push_back(ptr);
return *this;
}
void operator+=(Animal *arg) {
shared_ptr<Animal> ptr(arg);
vec.push_back(ptr);
}
void make_noise() {
vector<shared_ptr<Animal>>::iterator v = vec.begin();
while (v != vec.end()) {
(*v)->give_sound();
v++;
}
cout << endl;
}
private:
vector<shared_ptr<Animal>> vec;
};
int main() {
Herd herd;
Dog d1, d2;
Cat c1, c2;
cout << "sound 1: " << endl;
herd.make_noise();
herd += &d1;
herd += &c1;
cout << "sound 2: " << endl;
herd.make_noise();
herd += &d2;
herd += &c2;
cout << "sound 3: " << endl;
herd.make_noise();
//herd = herd - &d1;
//herd = herd - &d2;
cout << "sound 4: " << endl;
herd.make_noise();
return 0;
}
编辑:没有 vec.clear() 它也会崩溃。
【问题讨论】:
-
发布问题中的代码。
-
@molbdnilo 在这里
-
"我不熟悉智能指针,但我不得不在我的代码中使用它们来处理继承问题。" 我有点困惑。智能指针显然在这里不起作用,因为对象是在堆栈上分配的。但是一个普通的、愚蠢的指针应该工作得很好。为什么你认为在这里需要智能指针?
标签: c++ oop vector smart-pointers