我对大多数OO理论有了深刻的理解,但让我困惑的一件事是虚拟析构函数.
我认为无论什么以及链中的每个对象,析构函数总是会被调用.
你什么时候打算让它们成为虚拟的?为什么?
我如何投射到派生类?以下方法都会出现以下错误:
无法从BaseType转换为DerivedType.没有构造函数可以采用源类型,或构造函数重载解析是不明确的.
BaseType m_baseType;
DerivedType m_derivedType = m_baseType; // gives same error
DerivedType m_derivedType = (DerivedType)m_baseType; // gives same error
DerivedType * m_derivedType = (DerivedType*) & m_baseType; // gives same error
Run Code Online (Sandbox Code Playgroud) 我以以下简单形式提出我的问题:
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";
}
};
Run Code Online (Sandbox Code Playgroud)
我想将所有动物类型一起存储在单个容器中,例如:
vector<animal*> container;
barnyard.push_back(new animal());
barnyard.push_back(new dog());
barnyard.push_back(new cat());
Run Code Online (Sandbox Code Playgroud)
在代码的某个时刻,我需要将dog对象转换为cat对象。我需要进行的转换是设置一个新的dog对象,并用与cat对应的对象相同的索引号替换它。据我了解,dynamic_cast在这种情况下不起作用,并且基于将C ++强制转换为派生类的方法,因此提到这种转换不是一种好习惯。由于模型中的猫和狗具有不同的行为特性,因此我不想将它们的定义放入动物模型中。另一方面,将它们分别存储在不同向量中将很难处理。有什么建议么?