我以这种简单的形式提出我的问题:
class animal {
public:
animal() {
_name="animal";
}
virtual void makenoise(){
cout<<_name<<endl;
}
string get_name(){
return _name;
}
protected:
string _name;
};
class cat : public animal {
public:
cat() {
this->_name="cat";
}
};
class dog : public animal {
public:
dog() {
this->_name = "dog";
}
};
我想将所有动物类型一起存储在一个容器中,例如:
vector<animal*> container;
barnyard.push_back(new animal());
barnyard.push_back(new dog());
barnyard.push_back(new cat());
在我的代码中的某个时刻,我需要将狗对象转换为猫对象。在这种转换中,我所需要的只是设置一个新的狗对象,并将其替换为与猫对应物所在的相同索引号。据我了解,dynamic_cast
在这种情况下不起作用并基于C++ 强制转换为派生类 https://stackoverflow.com/questions/5313322/c-cast-to-derived-class,有人提到这样的转换不是一个好的做法。由于我的模型中的猫和狗具有不同的行为特性,因此我不想将它们的定义放入动物模型中。另一方面,将它们分别存储在不同的向量中将很难处理。有什么建议么?
You say:
我需要将狗对象转换为猫对象。
但是之后:
在这种转换中,我所需要的只是设置一个新的狗对象,并将其替换为与猫对应物所在的相同索引号。
需要转换或者更换吗??这是完全不同的操作。
要进行转换,您需要设置一个函数来接收一只狗并返回一只猫:
auto convertDogToCat(Dog const& dog) -> Cat {
auto cat = Cat{};
// fill cat's member using dog's values...
return cat;
}
但要替换,只需用新的重新分配即可:
// v--- a cat is currently there
barnyard[ii] = new Dog{};
// ^--- we replace the old pointer
// with one that points to a dog.
但这会造成内存泄漏,要消除泄漏,只需使用std::unique_ptr
:
#include <memory> // for std::unique_ptr
// The base class need a virtual destructor
class animal {
public:
virtual ~animal() = default;
// other members...
};
std::vector<std::unique_ptr<animal>> barnyard;
barnyard.emplace_back(std::make_unique<animal>());
barnyard.emplace_back(std::make_unique<dog>());
barnyard.emplace_back(std::make_unique<cat>());
barnyard[ii] = std::make_unique<Dog>();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)