创建一个打印函数,该函数将ostream作为参数并写入该流

Bap*_*ton 4 c++ operator-overloading ostream

我目前正在讨论有关C++中运算符重载的问题.我有个问题:

创建一个包含int的简单类,并将operator +作为成员函数重载.还提供了一个print()成员函数,它将一个ostream作为参数并打印到该ostream&.测试你的课程,以证明它正常工作.

我可以创建类并编写操作符+函数,但我真的不明白问题的第二部分.到目前为止,在我对c ++的研究中,我并没有真正遇到过ostream,因此我不确定是否有可能明确地创建这样的流.我尝试过使用:

std :: ostream o;

但是这会产生错误.有人可以请教我如何创建这个功能吗?

Moo*_*uck 9

到目前为止,在我对c ++的研究中,我并没有真正遇到过ostream,因此我不确定是否有可能明确地创建这样的流.我尝试过使用:std :: ostream o;

你一定错过了什么,因为ostream很重要.顺便说一句,std :: cout是std :: ostream类型的变量.用法或多或少是这样的

#include <iostream> //defines "std::ostream", and creates "std::ofstream std::cout"
#include <fstream> //defines "std::ofstream" (a type of std::ostream)
std::ostream& doStuffWithStream(std::ostream &out) { //defines a function
    out << "apples!";
    return out;
}
int main() {
    std::cout << "starting!\n"; 
    doStuffWithStream(std::cout); //uses the function

    std::ofstream fileout("C:/myfile.txt"); //creates a "std::ofstream"
    doStuffWithStream(fileout); //uses the function

    return 0;
}
Run Code Online (Sandbox Code Playgroud)