我正在使用(C++)庫,其中的對象需要使用流進行初始化。提供與該庫的示例代碼使用此代碼:避免while(!is_eof)
// Declare the input stream
HfstInputStream *in = NULL;
try
{
// This sets up the special stream object for the later object (see below)
in = new HfstInputStream("pathToFile.hfsto");
}
// catch errors...
// {omitted}
// Initialize the object
while (not in->is_eof()) {
if (in->is_bad())
{
std::cerr << "ERROR: Stream cannot be read." << std::endl;
exit(1);
}
// Here we initialize the object using the stream
HfstTransducer t(*in);
}
我的問題是該對象不能因爲作用域的while循環外使用。我必須聲明它與流(據我所知),所以我不能聲明,然後用循環內的流初始化它。
我的問題是(1)我錯了嗎?我能否以某種方式在循環外部實際聲明它? (2)是否有另一種(更好的)方法來完成此操作,以避免完成循環。例如,如果我使用try/catch並捕獲異常。
我對C++很陌生,希望找出最佳實踐,所以請讓我知道是什麼。謝謝。
另外,爲了清楚起見,我正在尋找一個可以使用此對象的持久版本的類,所以我不必每次都需要使用它們時不斷創建/銷燬這些對象。
PS:here's a link to the documentation for the object if it is relevant
編輯:如果我試圖聲明外循環的變量,然後初始化它,我得到一個錯誤
HfstTransducer t;
while (not in->is_eof()) {
t(*in);
}
// ERROR: main.cpp:47:0 main.cpp:47: error: no match for call to '(hfst::HfstTransducer) (hfst::HfstInputStream&)'
上午我試圖不正確初始化?
'HfstTransducer t(* in);'在循環範圍內。但'HfstInputStream * in'不是,你可以在循環之外訪問它,並用來初始化另一個'HfstTransducer'對象或者只使用'HfstInputStream'指針......當然,除非'HfstTransducer'構造函數具有移動語義和擦除' HfstInputStream * in'。 – lapk 2012-02-07 07:50:44
您的問題是您無法在循環之外訪問t(它是HfstTranducer類型的對象)? 如果是這樣,那麼你可以在堆的循環之外聲明它,並使用新運算符在循環內初始化它。 如果不是那麼我只是誤解了你的問題:P – Lefteris 2012-02-07 08:05:11
對不起,如果我不清楚。我的意思是我希望將HfstTransducer對象放在循環外部,並在HfstTransducer初始化後忘記流,而不是每次都創建一個新的HfstTransducer對象。如果這是可能的,這是我的目標。 – dougalg 2012-02-07 08:05:49