c++ - 多态继承不覆盖基类方法

标签 c++ inheritance vector polymorphism

我的基类:

class Item
{
protected:  
    int count;
    string model_name;
    int item_number;

public:
    Item();
    void input();
}

我的派生类:

class Bed : public Item
{
private:
    string frame;
    string frameColour;
    string mattress;

public:
    Bed();
    void input();
}

现在我所有的输入函数都试图做的是输出正在使用的方法:

void Item::input()
{ 
    cout<<"Item input"<<endl;
}

void Bed::input()
{
    cout<<" Bed Input"<<endl;
}

当我调用 main 中的函数时,我希望使用派生类输入,但目前是项目输入。

主要内容:

vector<Item> v;
Item* item;
item= new Bed;
v.push_back(*item);
v[count].input();
count++;

我已经按照我所拥有的一本书中列出的方法进行操作,但我想我可能对如何创建存储在 vector 中的新对象感到困惑。

任何帮助都会很棒, 谢谢

最佳答案

您还没有将您的方法标记为virtual

此外,因为您有对象的 vector ,而不是指针,所以您会遇到对象切片。尽管它可以编译,但它是不正确的。

正确的方法是使用指针 vector 或智能指针。

class Item
{
   //....
   virtual void input(); //mark method virtual in base class
};

class Bed : public Item
{
   //....
   virtual void input();
};


vector<Item*> v;
Item* item = new Bed;
v.push_back(item);
//...
//remember to free the memory
for ( int i = 0 ; i < v.size() ; i++ ) 
    delete v[i];

关于c++ - 多态继承不覆盖基类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10351570/

相关文章:

c++ - OpenAL:定位 freealut 或修复此代码

c++ - 如何禁用特定的未知 #pragma 警告(GCC 和/或 Clang)

java - Android - 类的空构造函数也会给出错误

c++ - 在 std::function 中返回初始值设定项列表而不是 vector

c++ - Excel 调用 C++ 程序的函数

c++ - 用 C++ 发出声音(哔)

c# - 覆盖被覆盖的方法 (C#)

c++ - 多重继承时不可能实现多态和动态绑定(bind)

c++ - 使用运算符重载添加到列表

安卓XML|了解 pathData 语法