c++ - 多态构造函数

标签 c++ inheritance

我的代码编译正常,但我遇到了特定部分未显示正确输出的问题。

这是我的基类

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 显示正确的输出,但是当我从主函数调用 getname 和 getnumber 时,程序为两者打印“1”,无论其中存储了什么。 我认为派生类可以使用基类方法,我错过了什么? 任何帮助都会很棒

谢谢

最佳答案

好吧,你的例子与多态无关。这里的原因是您没有使用任何虚函数。这是您可以使用的代码。

class Item
{
protected:

    std::string model_name;
    int item_number;

public:

    Item();
    Item(std::string& name, int number) : model_name(name), item_number(number) {};
    std::string getName(){return model_name;}
    int getNumber(){return item_number;}
};

class Bed : public Item
{
private:

    std::string frame;
    std::string frameColour;
    std::string mattress;

public:

    Bed();

    Bed(int number, std::string& name, std::string& frm, std::string& fclr, std::string& mtres) : Item(name, number), 
                                                                                                  frame(frm),
                                                                                                  frameColour(fclr), 
                                                                                                  mattress(mtres) {};
};

int main()
{
    int count = 0;
    std::vector<Item*> v;

    Item* item = new Bed(2, std::string("MyBed"), std::string("wood"), std::string("red"), std::string("soft"));
    std::cout << "working, new bed" << std::endl;
    v.push_back(item);

    std::cout << "working pushback" << std::endl;
    std::cout << " this is whats been stored:" << std::endl;
    std::cout << v[count]->getName() << std::endl;
    std::cout << v[count]->getNumber() << std::endl;

    ++count;

    getchar();
}    

关于c++ - 多态构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10413834/

相关文章:

c++ - 访问对象void pointer c++的成员

c++ - 图像处理-旋转和光学字符识别

c# - C# 中泛型类型的缺点

java - 为什么Java中不能扩展注解?

vb.net - 将 friend 类作为类型从公共(public)类传递到 friend 基类时出错

c++ - C++ 中有没有办法将父类转换/复制到子类中?

javascript - Qt:如何使用从 evaluateJavaScript 返回的 QVariant?

c++ - 为什么没有准确的C++反编译器?

c++ - 如何在 C++ 中创建包含子类的类的链表?

java - 如何实现父类(super class)对象转换为子类对象的效果?