如何从文本文件C++制作对象?

How to make object from text file C++?

本文关键字:作对 对象 C++ 文件 文本      更新时间:2023-10-16

我必须在我的项目中实现多态性。我有一个名为"帐户"的虚拟课程。然后有 4 个子类:美元、欧元、英镑和瑞士法郎。 我需要从这样的文本文件中读取当前余额:

USD 50
CHF 80
GBP 10
EUR 90

并根据货币创建一个子类。
每种货币都应该有自己的对象。在程序的后面,我将实现货币兑换,汇率将从文件中读取。我不知道如何从这些课程开始。我应该学习什么?

到目前为止我的代码:

class Account{
std::string currency;
public:
virtual void balance() = 0;
};
class currencyAcc: public Konto {
std::string currency;
float balance;
walutowe(std::string currency,float balance) {
this->currency= currency;
this->balance= balance;
}
void AccBallance() {
std::cout << balance<< std::endl;
}
};

我应该学习什么?

好吧,如果您已经涵盖了基础知识,那么您肯定需要一些练习和指导!

您可以有一个全局函数:

  • 读取文本文件块,
  • 动态解析和创建正确的对象(基于某些条件(,以及
  • 返回指向对象的指针(强制转换为基(:
Account * parseOne(std::fstream& file);    // Reference to opened file

即使你只是想要代码,你仍然需要通过解释。 :)
让我们从一般意义上看它。

读一行

很简单:

std::getline(file, line);

它。您还应该检查读取是否成功。

解析它

您可以按以下方式执行此操作:

std::stringstream parse_me(line);
parse_me >> some_data_1;
parse_me >> some_data_2;
...

创建对象...

在这里,您需要在currency_type的基础上创建它。做:

if(currency_type == "GBP")
{
new_currency_object = new GBP(balance);
}

对于每个派生类。

。和守则

把它放在一起:

Account * parseOne(std::fstream& file)     // Reference to opened file
{
// To read a line from the file
std::string line;
// If the read failed, return NULL
if(!std::getline(file, line))
{
return 0;
}
// Read success
// Using stringstream so that different types of data can be parsed
std::stringstream line_buffer(line);
// Declare variables to be parsed
std::string currency_type;
float balance;
// Now parse it (note the order!)
line_buffer >> currency_type >> balance;
// Create a pointer to base...
Account * new_currency_object;
// ...and create the object based on the currency_type
if(currency_type == "USD")
{
new_currency_object = new USD(balance);
}
... for each currency
// We are done, return the fruits of our labour
return new_currency_object;
}

(请注意,我假设您有一个USD(float balance)构造函数。如果没有,请将balance自己(
设置为:

// open the file
std::fstream currency_file("my_currencies.txt");
// Read a currency
Account * a_currency;
// When the read finishes, we get NULL
while(a_currency = parseOne(currency_file))
{
// do something with a_currency. Maybe:
// list_of_currencies.push_back(a_currency) it?
}

编辑:并确保在完成后释放内存!事实上,不再鼓励使用new和原始指针。感谢此评论的建议。
有关进一步阅读,请参阅如何在C++中正确实现工厂方法模式 .
祝你好运!

您需要一个接受构造函数中的货币代码的货币类。Currency 类的对象可以通过组合成为帐户的一部分,而不是具有数据类型字符串的当前货币。