我的代码编译得很好,但我遇到了某个特定部分无法显示正确输出的问题。
下面是我的基类
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‘。我认为派生类可以使用基类方法,但我错过了什么?任何帮助都是最好的
谢谢Hx
发布于 2012-05-02 20:37:10
count似乎与您的vector大小相同。在推回最后一个元素之后,您不会递增count,所以打印的是一个较旧的元素。
你为什么不试试:
cout<<v[v.size()-1]->getName<<endl;
cout<<v[v.size()-1]->getNumber<<endl;此外,您应该开始在构造函数中使用初始化列表:
Bed::Bed(int number, string name, string frm, string fclr, string mtres) :
  Item(name,number),
  frame(frm),
  frameColour(fclr),
  mattress(mtres)
{
}https://stackoverflow.com/questions/10413834
复制相似问题