gpt4 book ai didi

c++ - 多态构造函数

转载 作者:行者123 更新时间:2023-11-30 02:04:37 25 4
gpt4 key购买 nike

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

这是我的基类

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com