重载 << 以输出到文件中
Overloading << to output into a file
所以我有:
在我的 .h 中:
friend std::ofstream & operator <<(std::ofstream & output, myClass & s);
在我的.cpp
std::ofstream & operator <<(std::ofstream & output, myClass & s)
{
ofstream ofile << ("output.txt");
output << "Test" << endl;
return output;
}
我收到错误:
expected initializer before '<<' token
在`std::ofstream & operator <<(std::ofstream & output, myClass & s)
和
no match for 'operator<<' (operand types are 'std::ofstream {aka std::basic_ofstream}' and 'const char [5]')
在 ofstream ofile << ("output.txt");
有什么问题?`
`
您可能想要执行与以下类似的操作:
ofstream ofile{"output.txt"};
ofile << some_object;
这是调用 std::ofstream 的构造函数,随后写入指定的流,后者又写入文件。
将函数限制为 std::ofstream
通常不是一个好主意,因为它也可以与 任何 类型的 std::ostream
一起使用。当您将非 const
引用传递给打印函数时,它看起来也非常可疑。这意味着您正式允许打印具有副作用,即修改打印的对象!
出于这些原因,您应该更改此设置:
std::ofstream & operator <<(std::ofstream & output, myClass & s);
为此:
std::ostream & operator <<(std::ostream & output, myClass const& s);
您也不需要在运算符的实现中创建流实例。您收到对 one 的引用作为第一个参数。所以就这样做(当我们这样做时,避免 endl
除非你确切地知道你在做什么):
std::ostream & operator <<(std::ostream & output, myClass const& s);
{
output << "Test\n";
// output << s.some_member << "\n";
return output;
}
您现在只需将 std::ofstream
对象传递给该函数即可写入文件。您只需要创建对象,将文件名传递给它的构造函数:
myClass s;
std::ofstream os("output.txt");
os << s;
所以我有:
在我的 .h 中:
friend std::ofstream & operator <<(std::ofstream & output, myClass & s);
在我的.cpp
std::ofstream & operator <<(std::ofstream & output, myClass & s)
{
ofstream ofile << ("output.txt");
output << "Test" << endl;
return output;
}
我收到错误:
expected initializer before '<<' token
在`std::ofstream & operator <<(std::ofstream & output, myClass & s)
和
no match for 'operator<<' (operand types are 'std::ofstream {aka std::basic_ofstream}' and 'const char [5]')
在 ofstream ofile << ("output.txt");
有什么问题?`
`
您可能想要执行与以下类似的操作:
ofstream ofile{"output.txt"};
ofile << some_object;
这是调用 std::ofstream 的构造函数,随后写入指定的流,后者又写入文件。
将函数限制为 std::ofstream
通常不是一个好主意,因为它也可以与 任何 类型的 std::ostream
一起使用。当您将非 const
引用传递给打印函数时,它看起来也非常可疑。这意味着您正式允许打印具有副作用,即修改打印的对象!
出于这些原因,您应该更改此设置:
std::ofstream & operator <<(std::ofstream & output, myClass & s);
为此:
std::ostream & operator <<(std::ostream & output, myClass const& s);
您也不需要在运算符的实现中创建流实例。您收到对 one 的引用作为第一个参数。所以就这样做(当我们这样做时,避免 endl
除非你确切地知道你在做什么):
std::ostream & operator <<(std::ostream & output, myClass const& s);
{
output << "Test\n";
// output << s.some_member << "\n";
return output;
}
您现在只需将 std::ofstream
对象传递给该函数即可写入文件。您只需要创建对象,将文件名传递给它的构造函数:
myClass s;
std::ofstream os("output.txt");
os << s;