确定要使用的类
determining what class to use
我有一个关于解决这个问题的最佳方法的问题,我有确定将哪个类传递给我的重载运算符<<()函数。
我的 <<函数从输入文件中读取一行,对其进行标记化并将该数据插入到客户、Tour 或 GuidedTour 对象中,具体取决于该特定行的第一个标记
Tour 是 GuidedTour 的基础类,但客户根本不相关,所以我认为我不可以在它们之间使用强制转换(或者我可以吗?
这是代码:
for (unsigned int i = 0; i < inputFiles.size(); i++)
{
ifstream fin(inputFiles[i], ios_base::in);
int line = 0;
char c;
while (fin)
{ line++;
c = fin.peek(); //use peek() to check first char of next line
if (c == ios::traits_type::eof())
break;
// this is where i am having the trouble
else if (c == 'C')
Customer *temp = new Customer();
else if (c == 'g')
GuidedTour *temp = new GuidedTour();
else if (c == 't')
Tour *temp = new Tour();
else
throw boost::bad_lexical_cast();
try
{
fin >> *temp;
}
catch(boost::bad_lexical_cast&)
{
cerr << "Bad data found at line " << line
<< " in file "<< inputFile[i] << endl;
}
customers.push_back(temp);
}
fin.close();
}
很明显,我遇到了麻烦;因为我正在初始化条件块中的对象,所以在该块完成后它们不会持久化,但我不知道如何使它们持久化......还是不可能做我想要实现的目标?
我知道这不是一个非常直接的问题,我只是多年来一直在试图解决这个问题,所以任何建议将不胜感激。
编辑:是否可以做一些事情,比如在称为 temp 的循环开始时使用一个 void 指针,然后将其转换为条件中的对象,然后再将其传递给 fin <<*temp?
@guskenny83基本前提是声明一个 voir 指针并将值推入其中,只需记住正确引用/尊重,否则您将获得一些可爱的十六进制值打印。 作为一个简单的例子,我可以通过手动控制带有变量的类型来想到以下方法来做到这一点:
#include <iostream>
#include <stdio.h>
enum Type
{
INT,
FLOAT,
};
using namespace std;
void Print(void *pValue, Type eType)
{
using namespace std;
switch (eType)
{
case INT:
cout << *static_cast<int*>(pValue) << endl;
break;
case FLOAT:
cout << *static_cast<float*>(pValue) << endl;
break;
}
}
int main()
{
cout << "Hello World" << endl;
int me = 3;
void* temp;
if (me == 2)
{
int i = 12;
temp = &i;
}
else
{
float f = 3.2;
temp = &f;
}
if (me == 2)
{
Print(temp,INT);
}
else
{
Print(temp,FLOAT);
}
return 0;
}
我会尝试一种不同的方法,也许使用类层次结构的重组而不是空指针:它们允许你寻求的东西,但它们确实避免了类型检查......
希望这对您有所帮助:)
无论哪种方式,请通过一些反馈告诉我,我可以回复您。
相关文章:
- 没有找到相关文章