在何处放置过载<<代码? [英] Where to put overload<< code?

查看:77
本文介绍了在何处放置过载<<代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于正在使用toString()函数返回字符串的Foo类,我试图重载流运算符<< ;,并使用以下代码:

I am trying to overload the stream operator <<, for a class Foo which has already a toString() function returning a string, with the following code:

std::ostream &operator<<( std::ostream &flux, Foo const& foo )
{
    flux <<  foo.toString(); 
    return flux;
}

为了在main.cpp文件中使用它

我的问题是:这段代码放在哪里?

My question is: Where to put that piece of code?

  • 如果我将其放置在main.cpp中,则在使用前,它可以很好地工作,但是我可能想在其他文件中使用它.
  • 如果将其放置在foo.cpp中,则会出现无此功能"错误:

  • If I place it in the main.cpp, before its usage, it works well, but i may want to use it in other files.
  • If I place it in foo.cpp, I get a 'no such function' error:

src/main.cpp:77: error: no match for ‘operator<<’ in ‘std::cout << foo’

这很有意义,因为代码未包含在main.cpp文件中

which make sense since the code is not included to the main.cpp file

如果将其放在类声明之外的foo.h类头中,则会出现多个定义"错误:

If I place it in the foo.hclass header, outside class declaration, I get a 'multiple definition' error:

foo.o: In function `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Foo const&)':
foo.cpp:(.text+0x0): multiple definition of `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Matrix const&)'
bar.o:bar.cpp:(.text+0x0): first defined here

foo.h标头确实包含在不同的类/文件中,但是有一个ifdef防护,所以我不明白.

The foo.h header is indeed included in different classes/files, but there is a ifdef guard, so I don't understand this.

那我该怎么办?

推荐答案

有多个选项:

//foo.h
class Foo
{};
std::ostream &operator<<( std::ostream &s, Foo const& foo );

//foo.cpp
#include "foo.h"
std::ostream &operator<<( std::ostream &s, Foo const& foo )
{
    return s;
}

在类定义中将其定义为friend.

//Foo.h
class Foo
{
   friend std::ostream &operator<<( std::ostream &s, Foo const& foo )
   {
      return s;
   }
};

在类定义之外的标头中定义它,并将其标记为inline以防止出现多个定义.

Define it in the header, outside the class definition, and mark it as inline to prevent the multiple definition.

//Foo.h
class Foo
{
};

inline std::ostream &operator<<( std::ostream &s, Foo const& foo )
{
   return s;
}

这篇关于在何处放置过载&lt;&lt;代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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