如何在文件中打印并在 C++ 中使用具有相同功能的 cout?

How to print in a file and with cout with same function in c++?

我有一个像这样的简单打印功能:

template <class T>
void ArrayList<T>::print() const {
    //store array contents to text file
    for (int i = 0; i < length; i++)
    {
    cout << *(list + i) << endl;
    }
}

它打印数组中的值。我希望它像这样工作: 如果调用 ArrayList 的“打印”函数时不带任何参数,那么它会将信息写入标准输出流。但是,“ofstream”类型的变量应该将信息写入文件。

我将函数更改为写入文件,但现在如果我不传递参数,则会显示错误。有没有办法让它既写入文件(如果参数通过)又标准打印(如果没有参数)?

template <class T>
void ArrayList<T>::print(std::ofstream& os) const {
    //store array contents to text file
    for (int i = 0; i < length; i++)
    {
    os << *(list + i) << endl;
    }
}

您在这里可以做的是将 std::ostream& 作为您的参数。 然后 print 函数不关心数据输出到哪里。

static void print( std::ostream& os ) 
{
    os << "I don't care where this data is going\n";
}

int main( ) 
{
    // Pass it std::cout.
    print( std::cout );
    
    // Or pass it an std::fstream.
    std::fstream file{ "/Path/To/File/File.txt", std::ios::out };
    print( file );
}