解决输出运算符重定义问题

困扰我这么久一定要发文!!!

问题描述

在不同的文件中定义了多个类,对每个类都重载<<运算符,但是!!!问题来了
有的时候报错"找到一个或多个重定义"
有的时候呢,正常运行……
这就很恶心了
搜索了很多解决方法,比如说得最多的using namespace std;的问题,然而并没有什么用,最后翻墙谷歌了一下,不得不说,人家还是牛逼的
Google搜索的第一个推荐就是我搜索的关键词

multiple definition of operator<<(std::ostream&, Error const&)

感兴趣地可以看一下原问题解答

解决方法

template <class T> ostream& operator<<(ostream& out, const MyClass<T>& x)

改成template <class T> inline ostream& operator<<(ostream& out, const MyClass<T>& x)即可!!!

template <class T> ostream& operator<<(ostream& out, const MyClass<T>& x)

改成template <class T> inline ostream& operator<<(ostream& out, const MyClass<T>& x)即可!!!

template <class T> ostream& operator<<(ostream& out, const MyClass<T>& x)

改成template <class T> inline ostream& operator<<(ostream& out, const MyClass<T>& x)即可!!!

很简单吧,可就是这个问题困扰了我好久,我太lj了,哭……建议下次编程问题还是直接Google吧,哭……

报错原因

稍微介绍一下报错原因,如果不是内联函数的话,若重载<<运算符的实现函数所在的文件是myfile.h,那么在其他文件file1.cpp、file2.cpp……文件中#include "myfile.h",即包含这个文件,就会在file1.cpp、file2.cpp……文件中拥有多次对<<相同的定义,所以报错。

The problem is that this operator definition
ostream& operator<<(ostream& str, const Error& err) {
str << err.mError << " (priority " << err.mPriority << “)”;
return (str);
}
is placed by you in a header file. So if the header is included in more than one module you will have several definitions of the operator.
The simplest way to escape the error is to define the function as inline.
出处:http://www.cplusplus.com/forum/beginner/97276/

发布了96 篇原创文章 · 获赞 19 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Thera_qing/article/details/103301578