重载“<<<与结构(没有类)cout风格 [英] overloading "<<" with a struct (no class) cout style

查看:84
本文介绍了重载“<<<与结构(没有类)cout风格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构,我想使用'std :: cout'或一些其他输出流输出。
这是否可以不使用类?

I have a struct that I'd like to output using either 'std::cout' or some other output stream. Is this possible without using classes?

感谢

#include <iostream>
#include <fstream>
template <typename T>
struct point{
  T x;
  T y;
};

template <typename T>
std::ostream& dump(std::ostream &o,point<T> p) const{
  o<<"x: " << p.x <<"\ty: " << p.y <<std::endl;
}


template<typename T>
std::ostream& operator << (std::ostream &o,const point<T> &a){
  return dump(o,a);
}


int main(){
  point<double> p;
  p.x=0.1;
  p.y=0.3;
  dump(std::cout,p);
  std::cout << p ;//how?
  return 0;
}



我尝试了不同的语法,但我似乎无法使它工作。 p>

I tried different syntax' but I cant seem to make it work.

推荐答案

也许这是一个复制粘贴错误,但只有一些事情错了。首先,自由函数不能是 const ,但是你已经标记了 dump 。第二个错误是 dump 不返回一个值,这也很容易补救。修复这些和它应该工作:

Perhaps it's a copy-paste error, but there are just a few things wrong. Firstly, free-functions cannot be const, yet you have marked dump as such. The second error is that dump does not return a value, which is also easily remedied. Fix those and it should work:

template <typename T> // note, might as well take p as const-reference
std::ostream& dump(std::ostream &o, const point<T>& p)
{
    return o << "x: " << p.x << "\ty: " << p.y << std::endl;
}

这篇关于重载“&lt;&lt;&lt;与结构(没有类)cout风格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆