基本上我应该创建一个程序,用户在其中输入一些项目并从中创建对象,基本上我需要将对象存储在文件中,然后从文件中读取并在控制台窗口中输出对象属性。我遇到的问题是,当我从中创建一些对象并将这些对象存储在具有单独索引的独立数组的堆数组中时,即使我试图使用Item类的参数化构造函数创建这些对象时,我也无法理解参数化的构造函数被调用或未参数化,因为我得到的输出是一些垃圾值而不是我输入的值。所以请解决我的问题。
我尝试调用非参数化的构造函数来创建堆对象,但我不知道为什么在控制台窗口中输出时会得到一些垃圾值。
#include <iostream>
#include <string>
#include <fstream>
class Item {
private:
std::string name;
float price;
int quantity;
public:
std::string getname(void) {
return this - > name;
}
float getprice(void) {
return this - > price;
}
int getquantity(void) {
return this - > quantity;
}
void setname(std::string name) {
this - > name = name;
}
void setprice(float price) {
if (price > 0.0 f) {
this - > price = price;
} else {
this - > price = 0.1 f;
}
}
void setquantity(int quantity) {
if (quantity > 0) {
this - > quantity = quantity;
} else {
this - > quantity = 1;
}
}
Item() {
}
Item(std::string name, float price, int quantity);
friend std::ofstream & operator << (std::ofstream & ofs, Item & r);
friend std::ostream & operator << (std::ostream & out, Item & i);
friend std::ifstream & operator >> (std::ifstream & ifs, Item & i);
};
Item::Item(std::string name, float price, int quantity) {
this - > name = name;
this - > price = price;
this - > quantity = quantity;
}
std::ofstream & operator << (std::ofstream & ofs, Item & r) {
ofs << r.name << "\n";
ofs << r.price << "\n";
ofs << r.quantity << "\n";
return ofs;
}
std::ifstream & operator >> (std::ifstream & ifs, Item & i) {
ifs >> i.name >> i.price >> i.quantity;
return ifs;
}
std::ostream & operator << (std::ostream & out, Item & i) {
out << i.name << "\n";
out << i.price << "\n";
out << i.quantity << "\n";
return out;
}
int main(void) {
int n;
std::string nm;
float prc;
int qty;
std::cout << "Input the number of items : " << "\n";
std::cin >> n;
Item * ptr[n];
for (int i = 0; i < n; i++) {
std::cout << "Please input the " << i + 1 << " item's name : " << "\n";
std::cin >> nm;
std::cout << "Please input " << i + 1 << " item price :" << "\n";
std::cin >> prc;
std::cout << "Please input " << i + 1 << " item quantity : " << "\n";
std::cin >> qty;
ptr[i] = new Item(nm, prc, qty);
}
/*std::cout<<"\n\n";
for(int i=0;i<n;i++){
std::cout<<i+1<<" Items name is : "<<ptr[i]->getname()<<"\n";
std::cout<<i+1<<" Items price is : "<<ptr[i]->getprice()<<"\n";
std::cout<<i+1<<" Items quantity is : "<<ptr[i]->getquantity()<<"\n";
std::cout<<"-----------------------------------\n";
} */
std::ofstream ofs("STUDENT.txt");
for (int i = 0; i < n; i++) {
ofs << * ptr[i];
}
Item item;
std::ifstream ifs("STUDENT.txt");
for (int i = 0; i < 3; i++) {
ifs >> item;
std::cout << "Item : " << i + 1 << "\n" << item << "\n";
}
delete[] ptr;
return 0;
}