C++ 使用结构(无类)cout 样式重载“<<”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2719136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:28:40  来源:igfitidea点击:

overloading "<<" with a struct (no class) cout style

c++stloperator-overloading

提问by monkeyking

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?

我有一个结构,我想使用“std::cout”或其他一些输出流来输出。这可能不使用类吗?

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.

我尝试了不同的语法'但我似乎无法让它工作。

回答by GManNickG

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 dumpas such. The second error is that dumpdoes not return a value, which is also easily remedied. Fix those and it should work:

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

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

回答by Joris Timmermans

For all intents and purposes, structs areclasses 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++.

出于所有意图和目的,结构C++中的类,除了它们的成员默认为 public 而不是 private。由于优化,可能存在细微的特定于实现的差异,但这些对标准功能没有影响,这与 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;
}