热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何使用cout

myclassisaC++classwrittenbymeandwhenIwrite:myclass是我写的c++类,当我写的时候:myclassx;cout<

myclass is a C++ class written by me and when I write:

myclass是我写的c++类,当我写的时候:

myclass x;
cout <

how to output 10 or 20.2, like an integer or a float value?

如何输出10或20.2,比如整数或浮点数?

3 个解决方案

#1


59  

Typically by overloading operator<< for your class:

通常通过重载操作符<<<<<为类:

struct myclass { 
    int i;
};

std::ostream &operator<<(std::ostream &os, myclass const &m) { 
    return os <

#2


18  

You need to overload the << operator,

需要重载<<<运算符,

std::ostream& operator<<(std::ostream& os, const myclass& obj)
{
      os <

Then when you do cout < (where x is of type myclass in your case), it would output whatever you've told it to in the method. In the case of the example above it would be the x.somevalue member.

然后,当您执行cout

If the type of the member can't be added directly to an ostream, then you would need to overload the << operator for that type also, using the same method as above.

如果成员的类型不能直接添加到ostream中,那么您还需要使用与上面相同的方法重载该类型的<<<运算符。

#3


8  

it's very easy, just implement :

这很容易实现:

std::ostream & operator<<(std::ostream & os, const myclass & foo)
{
   os <

You need to return a reference to os in order to chain the outpout (cout <

您需要返回一个对os的引用来链接outpout (cout


推荐阅读
author-avatar
手机用户2502855767
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有