是否可以覆盖c ++运算符<<头文件中的结构? [英] is it possible to override the c++ operator<< for a struct in a header file?

查看:75
本文介绍了是否可以覆盖c ++运算符<<头文件中的结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过覆盖运算符<<来打印出结构中的字段.如果将替代放置在cpp文件中,则可以正常工作,但是我希望将其放置在头文件中.

I am trying to print out the fields in a struct by overriding operator<<. This works fine if I place the override in a cpp file, however I would like to have it in my header file.

但是,当我这样做时,会出现错误:

However when I do, I get the error:

  multiple definition of `operator<<(std::basic_ostream<char, std::char_traits<char> >&, test)' 

头文件中是否可以包含?

Is it possible to have in the header file?

test.h
#ifndef TEST_H
#define TEST_H
struct test{
    int a;
    int b;
    int c;
};


  std::ostream& operator<< (std::ostream& o, const test& t){
       o <<"{ " << t.a << " }" << endl;
       return o;
  }

#endif

推荐答案

与任何函数一样,如果您在标头中定义它,请使其内联:

As with any function, if you define it in a header, make it inline:

inline std::ostream& operator<< (std::ostream& o, const test& t)
^^^^^^

这放宽了一个定义规则",允许在任何包含标头的翻译单元中进行定义.

This relaxes the One Definition Rule, allowing a definition in any translation unit that includes the header.

这篇关于是否可以覆盖c ++运算符&lt;&lt;头文件中的结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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