我正在尝试使用paymentList向量,该向量在向量内部包含Cash,Check和Credit对象(它们是派生的派生类)。
我声明了这样的矢量:
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));
}
我现在想将此向量保存到文件中。我已经启动了保存功能,但我不确定从哪里开始:
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";
}
任何帮助将不胜感激:)
答案 0 :(得分:4)
这是完全错误的方法。
更好的方法是运行时多态性。在基类中声明一个名为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
}
};
然后使用Save
类型的指针调用Payment*
。
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 ++中的运行时多态性。