我的代码编译得很好,但我遇到了一个特定部分没有显示正确输出的问题。
这是我的基类
class Item
{
protected:
//int count;
string model_name;
int item_number;
public:
Item();
Item(string name, int number);
string getName(){return model_name;}
int getNumber(){return item_number;}
这是我的派生类:
class Bed : public Item
{
private:
string frame;
string frameColour;
string mattress;
public:
Bed();
Bed(int number, string name, string frm, string fclr, string mtres);
函数定义:
Bed::Bed(int number, string name, string frm, string fclr, string mtres)
{
model_name=name;
item_number=number;
frame=frm;
frameColour=fclr;
mattress=mtres;
cout<<model_name<<item_number<<frame<<frameColour<<mattress<<endl;
}
导致问题的主要部分:
Item* item= new Bed(number, name, material, colour, mattress);
cout<<"working, new bed"<<endl;
v.push_back(item);
cout<<"working pushback"<<endl;
cout<<" this is whats been stored:"<<endl;
cout<<v[count]->getName<<endl;
cout<<v[count]->getNumber<<endl;
count++;
当程序执行时,构造函数中的 cout 会显示正确的输出,但是当我从 main 函数调用 getname 和 getnumber 时,无论其中存储了什么,程序都会为两者打印 '1'。我认为派生类可以使用基类方法,我错过了什么?任何帮助都会很棒
谢谢你