我的基类:
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/