相关疑难解决方法(0)

何时使用虚拟析构函数?

我对大多数OO理论有了深刻的理解,但让我困惑的一件事是虚拟析构函数.

我认为无论什么以及链中的每个对象,析构函数总是会被调用.

你什么时候打算让它们成为虚拟的?为什么?

c++ polymorphism shared-ptr virtual-destructor

1420
推荐指数
13
解决办法
66万
查看次数

C++转换为派生类

我如何投射到派生类?以下方法都会出现以下错误:

无法从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)

c++ inheritance

45
推荐指数
3
解决办法
11万
查看次数

动态转换派生类的需求:寻找替代方法

我以以下简单形式提出我的问题:

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 ++强制转换为派生类的方法,因此提到这种转换不是一种好习惯。由于模型中的猫和狗具有不同的行为特性,因此我不想将它们的定义放入动物模型中。另一方面,将它们分别存储在不同向量中将很难处理。有什么建议么?

c++ polymorphism inheritance

2
推荐指数
1
解决办法
93
查看次数