gpt4 book ai didi

c++ - 将变量数据发送到其他类时出现问题

转载 作者:行者123 更新时间:2023-11-28 05:56:17 24 4
gpt4 key购买 nike

//元素.h

class Items
{
public:
Items();
Items(string, string, double, int, int);
//Item setters
void setDesciption(string);
void setSku(int);
void setLocation(int);
void setSupplier(string);
void setCost(double);

//Item getters
string getDescription();
int getSku();
int getLocation();
string getSupplier();
double getCost();
private:
//Item variables
string _description;
string _supplier;
double _cost;
int _sku;
int _location;
};

//items类中的构造函数

Items::Items(string description, string supplier, double cost, int sku, int location)
{
setDesciption(description);
setSupplier(supplier);
setCost(cost);
setSku(sku);
setLocation(location);
}

//这是添加项类//此函数旨在通过其默认构造函数传递项目类中的变量来设置它们的值。//现在我测试了在 main() 中调用 AddOrDeleteItems 函数,它工作得很好,但是当我在另一个类文件中尝试它时(比如添加项目类),items.h 文件中的变量永远不会设置,并返回它们的默认值。

void AddOrDeleteItems::newItem()
{
string description;
string supplier;
double cost;
int sku;
int location;
//Run checks on things like sku length, location.
cout << "Add a new product please enter the following.\n\n";
cout << "Description: ";
getline(cin, description);
cout << "\nSupplier: ";
getline(cin, supplier);
cout << "\nCost: ";
cin >> cost;
cout << "\nSku: ";
cin >> sku;
cout << "\nLocation: ";
cin >> location;

Items ItemsObj(description, supplier, cost, sku, location);
}

如果有帮助,请编辑添加我的 getter 和 setter...(还修复了我的 setter 和其余代码中的拼写错误...大声笑)

//Item Setters

void Items::setDescription(string x)
{
_description = x;
}
void Items::setSku(int x)
{
_sku = x;
}
void Items::setLocation(int x)
{
_location = x;
}
void Items::setSupplier(string x)
{
_supplier = x;
}
void Items::setCost(double x)
{
_cost = x;
}

//Item Getters
string Items::getDescription()
{
return _description;
}
int Items::getSku()
{
return _sku;
}
int Items::getLocation()
{
return _location;
}
string Items::getSupplier()
{
return _supplier;
}
double Items::getCost()
{
return _cost;
}

最佳答案

AddOrDeleteItems::newItem() 的末尾,您执行 Items ItemsObj(description, supplier, cost, sku, location); 因此您声明了一个实例Items 作为函数堆栈中的局部变量,然后继续从该函数返回,完全忘记这个局部变量曾经存在过。因此,您实际上并没有创建任何新的 Items 实例。也许你的意思是:

返回新项目(描述、供应商、成本、sku、位置);

还有:那个东西应该叫“Item”,而不是“Items”。

另外:一个名为“AddOrDeleteItems”的类被歪曲为一个概念,它的名字让我感到恶心。

关于c++ - 将变量数据发送到其他类时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34110976/

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