2013-10-17 41 views
0

我對解決這個問題,我有確定哪些類傳遞給我的重載操作< <()函數的最佳方式問題..確定使用哪個類

我< <函數讀取一行從輸入文件中將其標記並將該數據插入到Customer,Tour或GuidedTour對象中,具體取決於該特定行的第一個標記

Tour是GuidedTour的基類,但Customer根本不相關,所以我不認爲我可以使用他們之間的演員(或者我可以嗎?)

這裏是代碼:

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

其明顯的在那裏我遇到的麻煩;因爲我正在初始化條件塊內的對象,所以在塊完成後它們不會繼續存在,但我不知道如何讓它們持續下去。或者它只是不可能做到我想要實現的目標?

我明白這不是一個很直接的問題,我剛剛被抨擊我的頭撞牆試圖解決這個問題的年齡,所以任何建議將不勝感激..

編輯:是有可能做一些事情,比如在循環的開始處使用一個void指針,稱爲temp,然後在將它傳遞給條件中的一個對象之前將它傳遞給finder < < * temp?

+0

你可以讓你的所有類共享一個通用的基類嗎? – GWW

+0

不,不幸的是,他們不能.. – guskenny83

+1

[boost :: any](http://www.boost.org/doc/libs/1_54_0/doc/html/any.html)也可能是一個不錯的選擇,因爲你是已經使用'boost' – GWW

回答

0

@ guskenny83 基本的前提是聲明一個voir指針並將值推入,只要記得正確引用/ deference,或者您將得到一些可愛的十六進制值打印。舉一個簡單的例子,我可以通過使用變量手動控制類型覺得以下方式做到這一點:

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

我會嘗試不同的方法,可能使用類層次結構的重組,而不是空指針然而, :它們允許你追求什麼,但他們並避免類型檢查....

希望這有助於你:)

讓我知道有一些反饋無論哪種方式,我可以回覆你。

相關問題