overloading “<<” with a struct (no class) co

2020-03-24 03:12发布

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?

Thanks

#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;
}

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

2条回答
ゆ 、 Hurt°
2楼-- · 2020-03-24 03:55

For all intents and purposes, structs are classes in C++, except that their members default to public instead of private. There are potentially minor implementation-specific differences because of optimization but these have no effect on the standard functionality which is the same for classes and structs in C++.

Secondly, why have the "dump" function? Just implement it directly in the stream operator:

template<typename T>
std::ostream& operator << (std::ostream& o, const point<T>& a)
{
    o << "x: " << a.x << "\ty: " << a.y << std::endl;
    return o;
}
查看更多
smile是对你的礼貌
3楼-- · 2020-03-24 04:08

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;
}
查看更多
登录 后发表回答