多态继承不覆盖基类方法 [英] Polymorphism inheritance not overriding base class method
问题描述
我的基类:
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();
}
现在我所有的输入函数都在尝试输出正在使用的方法:
for now all my input function is trying to do is output which method is being used:
void Item::input()
{
cout<<"Item input"<<endl;
}
void Bed::input()
{
cout<<" Bed Input"<<endl;
}
当我在 main 中调用函数时,我希望使用派生类输入,但目前项目输入是.
when I call the function in main I'd like the derived class input to be used but at present the item input is.
主要内容:
vector<Item> v;
Item* item;
item= new Bed;
v.push_back(*item);
v[count].input();
count++;
我遵循了我所拥有的书中介绍的方法,但我想我可能对如何创建存储在向量中的新对象感到困惑.
I have followed the method laid out in a book I have but I think i may be confused about how to create new objects stored in the vector.
任何帮助都会很棒,谢谢高
Any help would be great, Thanks Hx
推荐答案
您尚未将您的方法标记为 virtual
.
You haven't marked your method as virtual
.
此外,因为您有一个vector
对象,而不是指针,所以您会遇到对象切片.虽然它会编译,但它是不正确的.
Also, because you have a vector
of objects, not pointers, you'll run into object slicing. Although it will compile, it isn't correct.
正确的方法是使用指针向量或智能指针.
The proper way is having a vector of pointers or smart pointers.
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];
这篇关于多态继承不覆盖基类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!