加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 10:19:58 所属栏目:百科 来源:网络整理
导读:我目前正在讨论有关C中运算符重载的问题.我有个问题: 创建一个包含int的简单类,并将运算符作为成员函数重载.还提供了一个print()成员函数,它具有一个ostream和amp;作为一个论点并打印到那个ostreamamp ;.测试你的课程,以证明它正常工作. 我可以创建类并编写
我目前正在讨论有关C中运算符重载的问题.我有个问题:

创建一个包含int的简单类,并将运算符作为成员函数重载.还提供了一个print()成员函数,它具有一个ostream和amp;作为一个论点并打印到那个ostream&amp ;.测试你的课程,以证明它正常工作.

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

std :: ostream o;

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

解决方法

So far in my study of c++ I havent really come across ostream’s and as
such am not sure if its possible to explicitly create such a stream. I
have tried using: 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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读