0

i have a question about the best way to solve this problem i have with determining what class to pass to my overloaded operator<<() function..

my << function reads a line from the input file, tokenises it and inserts that data into either a Customer, Tour or GuidedTour object, depending on the first token for that particular line

Tour is the base class of GuidedTour, but Customer is not related at all, so i dont think i can use a cast between them (or can i?)

here is the code:

 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();
}

its obvious where i am having the trouble; because i am initialising the objects inside the conditional blocks, they wont persist after that block is finished, but i have no idea how to make them persist.. or is it just not possible to do what i am trying to achieve?

i understand this is not a very direct question, i've just been bashing my head against a brick wall trying to solve this problem for ages, so any advice would be greatly appreciated..

EDIT: is it possible to do something like use a void pointer at the start of the loop called temp, and then cast it to an object within the conditionals before passing it to fin << *temp?

4

1 回答 1

0

@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;
}

我会尝试一种不同的方法,也许使用类层次结构的重组而不是空指针:它们允许你寻找什么,但它们确实避免了类型检查......

希望这对你有帮助:)

无论哪种方式,请告诉我一些反馈,我可以回复您。

于 2013-10-17T13:08:11.303 回答