我正在尝试使用一个 paymentList vector ,它在 vector 中包含 Cash、Check 和 Credit 对象(它们是 Payment 的派生类)。
我这样声明 vector :
typedef std::vector<Payment*> ListOfPayments;
我这样添加付款:
std::cout << "How would you like to pay?" << std::endl;
std::cout << "1. Cash" <<std::endl;
std::cout << "2. Credit"<<std::endl;
std::cout << "3. Cheque"<<std::endl;
std::cin >> choice;
while(choice < 1 || choice > 3)
{
std::cout<<"Please enter a correct number from 1 to 3"<<std::endl;
std::cin >> choice;
}
if(choice == 1)
{
paymentList->push_back(addCash(paymentId,orderId));
}
else if(choice == 2)
{
paymentList->push_back(addCredit(paymentId,orderId));
}
else
{
paymentList->push_back(addCheque(paymentId,orderId));
}
我现在想将这个 vector 保存到一个文件中。我已经启动了一个保存功能,但我不确定从这里去哪里:
void savePayment(ListOfPayments *paymentList)
{
int method;
Cheque * pCheque = dynamic_cast<Cheque *>(paymentList->at(paymentList->size()-1));
Cash * pCash = dynamic_cast<Cash *>(paymentList->at(paymentList->size()-1));
Credit * pCredit = dynamic_cast<Credit *>(paymentList->at(paymentList->size()-1));
std::ofstream* save = new std::ofstream(); // creates a pointer to a new ofstream
save->open("Payments.txt"); //opens a text file called payments.
if (!save->is_open())
{
std::cout<<"The file is not open.";
}
else
{
*save << paymentList->size() << "\n";
ListOfPayments::iterator iter = paymentList->begin();
while(iter != paymentList->end()) //runs to end
{
method = (*iter)->getMethod();
*save << method << "\n";
if(method == 1)
{
pCash->saveCashPayments(save);
}
else if(method == 2)
{
pCredit->saveCreditPayments(save);
}
else
{
pCheque->saveChequePayments(save);
}
iter++;
}
save->close();
delete save;
}
}
如果我保存一种类型的付款,它会起作用,但是一旦我在列表中有两个或更多付款,我就会收到违规读取位置错误。我猜这与类型转换错误或其他原因有关?以防我错了这里是我的保存函数的示例,该函数基于方法变量运行。
void Cash::saveCashPayments(std::ofstream* save)
{
*save << this->cashTendered << "\n";
*save << this->getId() << "\n";
*save << this->getAmount() << "\n";
*save << this->getOrderId() << "\n";
*save << this->getMethod() << "\n";
}
任何帮助将不胜感激:)
最佳答案
这是完全错误的做法。
更好的方法是运行时多态性。在基类中声明一个名为Save
的虚函数,并在每个派生类中定义它。
例如,如果 Payment
是基类,那么这样做:
class Payment
{
public:
virtual void Save(std::ostream & out) = 0;
};
然后在所有派生类中实现Save
。
class Cheque : public Payment
{
public:
virtual void Save(std::ostream & out)
{
//implement it
}
};
class Cash : public Payment
{
public:
virtual void Save(std::ostream & out)
{
//implement it
}
};
class Credit : public Payment
{
public:
virtual void Save(std::ostream & out)
{
//implement it
}
};
然后使用Payment*
类型的指针调用Save
。
void savePayment(ListOfPayments & payments)
{
std::ofstream file("Payments.txt");
for(ListOfPayments::iterator it = payments.begin(); it != payments.end(); ++it)
{
it->Save(file);
}
}
无需通过指针传递payment
;也不要使用 new std::ofstream
。
阅读 C++ 中的运行时多态性。
关于c++ - 使用类型转换在单个 vector 中包含不同的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8376945/