如何从文本文件C++制作对象?
How to make object from text file C++?
我必须在我的项目中实现多态性。我有一个名为"帐户"的虚拟课程。然后有 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 类的对象可以通过组合成为帐户的一部分,而不是具有数据类型字符串的当前货币。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 构造对象的歧义
- 使用"std::unordereded_map"映射到"std::list"对象