我必须在我的项目中实现多态。我有一个名为“帐户”的虚拟类。然后有 4 个子类:美元、欧元、英镑和瑞士法郎。我需要从这样的文本文件中读取当前余额:
USD 50
CHF 80
GBP 10
EUR 90
Run Code Online (Sandbox Code Playgroud)
并根据货币创建一个子类。
每种货币都应该有自己的对象。稍后在程序中,我将实现货币兑换,将从文件中读取汇率。我不知道如何开始这些课程。我应该学习什么?
到目前为止我的代码:
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;
}
};
Run Code Online (Sandbox Code Playgroud)
我应该学习什么?
好吧,如果您已经涵盖了基础知识,那么您肯定需要一些练习和指导!
你可以有一个全局函数:
Account * parseOne(std::fstream& file); // Reference to opened file
Run Code Online (Sandbox Code Playgroud)
即使您只想要代码,您仍然必须经过解释。:)
让我们从一般意义上来看待它。
很简单:
std::getline(file, line);
Run Code Online (Sandbox Code Playgroud)
它。您还应该检查读取是否成功。
你可以这样做:
std::stringstream parse_me(line);
parse_me >> some_data_1;
parse_me >> some_data_2;
...
Run Code Online (Sandbox Code Playgroud)
在这里,您需要在currency_type. 做:
if(currency_type == "GBP")
{
new_currency_object = new GBP(balance);
}
Run Code Online (Sandbox Code Playgroud)
对于每个派生类。
把它放在一起:
if(currency_type == "GBP")
{
new_currency_object = new GBP(balance);
}
Run Code Online (Sandbox Code Playgroud)
(请注意,我假设您有一个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?
}
Run Code Online (Sandbox Code Playgroud)
编辑:并确保在完成后释放内存!事实上,不再鼓励使用new和 原始指针。感谢这条评论的建议。
如需进一步阅读,请参阅如何在 C++ 中正确实现工厂方法模式
。
祝你好运!
| 归档时间: |
|
| 查看次数: |
614 次 |
| 最近记录: |