![](/img/trans.png)
[英]Can const member variable of class be initialized in a method instead of constructor?
[英]Can I use a member variable of type ofstream initialized in the class constructor?
我在聲明繼承的 class 的構造函數時遇到問題。
class Report{
public:
string fileName;
std::ofstream outputFile;
Report(string fileName, ofstream outputFile) {
fileName = fileName;
outputFile = outputFile; //<-- error here
}
void returnFile(string, ofstream);
void Report::returnFile(string name, ofstream file){
file.open(name);
}
};
class financialReport: public Report{
public:
void electorateHappenings();
void electorialImpact();
double finances();
void writetoFile();
financialReport(string fileName, ofstream outputFile)
:Report(fileName, outputFile) { } //<-- error here
};
錯誤發生在最后一行的第 3 行:Report(fileName, outputFile)
。
此行產生錯誤:
function "std::basic_ofstream<_CharT, _Traits>::basic_ofstream(const
std::basic_ofstream<_CharT, _Traits> &) [with _CharT=char,
_Traits=std::char_traits<char>]" (declared at line 848 of
"C:\MinGW\lib\gcc\mingw32\9.2.0\include\c++\fstream") cannot be referenced
-- it is a deleted function
不能創建一個包含ofstream
的構造函數嗎?
該錯誤也發生在第 9 行,其中outputFile = outputFile
。
謝謝你。
不能復制傳遞,不能復制一個,但是可以引用傳遞,在class的初始化列表中初始化:
class Report {
public:
string fileName;
std::ofstream &outputFile; //reference here
// reference parameter, and initializer list
Report(string fileName, ofstream &outputFile) : outputFile(outputFile) {
fileName = fileName;
}
//...
};
在financialReport
報告中做同樣的事情:
financialReport(string fileName, ofstream& outputFile) : Report(fileName, outputFile) {}
^
請注意,這是問題中提出的問題的解決方案,正常情況下,但在更深入的分析中,雖然您沒有詳細說明您想要實現的目標,但我不會 go 這么說一種錯誤的方法,但很有可能您可以以更好的方式構建您的程序。
是的,您可以,但錯誤告訴您不能復制std::ofstream
的 object 。
根據您想要執行的操作,有兩種方法可以處理它。
將std::ofstream
的所有權傳遞給您新創建的 object:
Report(string fileName, ofstream outputFile) :
fileName{std::move(outputFile)},
outputFile{std::move(outputFile)}
{
}
//creation of object:
std::ofstream ofs {"filename.txt"};
Report report {"filename.txt", std::move(ofs)};
//ofs is empty here, it's whole content has been transferred to report object
傳遞對現有std::ofstream
object 的引用:
class Report{
public:
string fileName;
std::ofstream& outputFile;
Report(string fileName, ofstream& outputFile) :
fileName{std::move(outputFile)},
outputFile{outputFile}
{
}
//creation of object:
std::ofstream ofs {"filename.txt}";
Report report {"filename.txt", ofs};
//you can use ofs from both here and from inside of report, but
//you have to ensure that ofs lives as long as report will use it or else you will enter Undefined Behaviour land
注意:如果您希望 class 成員和構造函數 arguments 具有相同的名稱,則需要像我一樣使用成員初始化器列表。 如果您決定使用引用,則也需要使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.