[問題] ofstream怎麼在constructor初始化?

看板C_and_CPP (C/C++)作者時間13年前 (2012/12/16 00:05), 編輯推噓2(209)
留言11則, 5人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) linux 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) no 問題(Question): 如果在一個自訂的class叫Test裡有一個data member為ofstream record 請問要怎麼在這個class的constructor初始化? 錯誤結果(Wrong Output): 程式碼(Code):(請善用置底文網頁, 記得排版) public: Test(): record(new ofstream("record")) {} 補充說明(Supplement): 上述的code會出現以下error: 對 「std::basic_ofstream<char>::basic_ofstream(std::ofstream*)」 的呼叫沒有匹 配的函式 ../../include/god.h:18:110: 附註: candidates are: /usr/include/c++/4.6/fstream:629:7: 附註: std::basic_ofstream<_CharT, _Traits>::basic_ofstream(const char*, std::ios_base::openmode) [with _CharT = char, _Traits = std::char_traits<char>, std::ios_base::openmode = std::_Ios_Openmode] /usr/include/c++/4.6/fstream:629:7: 附註: no known conversion for argument 1 from 「std::ofstream* {aka std::basic_ofstream<char>*}」 to 「const char*」 /usr/include/c++/4.6/fstream:614:7: 附註: std::basic_ofstream<_CharT, _Traits>::basic_ofstream() [with _CharT = char, _Traits = std::char_traits<char>] /usr/include/c++/4.6/fstream:614:7: 附註: candidate expects 0 arguments, 1 provided /usr/include/c++/4.6/fstream:588:11: 附註: std::basic_ofstream<char>::basic_ofstream(const std::basic_ofstream<char>&) /usr/include/c++/4.6/fstream:588:11: 附註: no known conversion for argument 1 from 「std::ofstream* {aka std::basic_ofstream<char>*}」 to 「 const std::basic_ofstream<char>&」 請問一下各位高手 該怎麼宣告才不會錯呢@@ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.25.108

12/16 00:08, , 1F
不要 new
12/16 00:08, 1F

12/16 00:08, , 2F
: record("record")
12/16 00:08, 2F
謝謝PkmX大大!!!! ※ 編輯: toshiba011 來自: 140.112.25.108 (12/16 00:17)

12/16 01:12, , 3F
重點應該是要了解為什麼不要new吧= =a
12/16 01:12, 3F
可以請大大說明一下嗎? ※ 編輯: toshiba011 來自: 140.112.245.82 (12/16 02:21)

12/16 13:39, , 4F
預期reference, 傳入的是pointer
12/16 13:39, 4F

12/16 17:59, , 5F
http://bpaste.net/show/64700/ 如果在class裏面宣告
12/16 17:59, 5F

12/16 18:02, , 6F
就用個initialization list吧,而且是在constructor 時做
12/16 18:02, 6F

12/16 18:02, , 7F
sorry, 講話有點顛倒(!@#$!%^#$^) 希望你看的懂
12/16 18:02, 7F

12/16 19:40, , 8F
他是用 initialization list 啊 只是弄錯 () 裡是什麼東西
12/16 19:40, 8F

12/16 19:41, , 9F
這東西的 () 裡面的東西是直接傳給那個物件的 ctor 的參數
12/16 19:41, 9F

12/16 19:41, , 10F
所以不需要另外寫一次 ostream 或 new ostream 什麼的
12/16 19:41, 10F

12/16 19:42, , 11F
直接把要丟的參數放進去 (在此就是 "record" 這個檔名) 即可
12/16 19:42, 11F
文章代碼(AID): #1Gp9_FdN (C_and_CPP)
文章代碼(AID): #1Gp9_FdN (C_and_CPP)