我是C++的新手(我来自C#)。
我在命名空间中有这个结构:
#pragma once
namespace utils {
struct astTime
{
int hour;
int min;
double secs;
};
double round(double number, int decPlace);
}
我还有一个已实现
round
函数的源文件。为了在Boost测试中使用该结构,我在Boost测试文件(.cpp)中定义了这两个运算符:
namespace utils {
bool operator ==(utils::astTime const &left, utils::astTime const &right)
{
return(
left.secs == right.secs
&& left.min == right.min
&& left.hour == right.hour);
}
std::ostream& operator<<(std::ostream& os, const utils::astTime& dt)
{
os << dt.hour << "h " << dt.min << "m " << dt.secs << "s" << std::endl;
return os;
}
}
我必须在哪里声明这两个运算符(以及如何声明)?
我已将其移至头文件(因为,我不知道将其声明为),请通过以下方式将它们从增强测试源文件中删除:
#pragma once
#include <iostream>
namespace utils {
struct astTime
{
int hour;
int min;
double secs;
};
bool operator ==(utils::astTime const &left, utils::astTime const &right)
{
return(
left.secs == right.secs
&& left.min == right.min
&& left.hour == right.hour);
}
std::ostream& operator<<(std::ostream& os, const utils::astTime& dt)
{
os << dt.hour << "h " << dt.min << "m " << dt.secs << "s" << std::endl;
return os;
}
double round(double number, int decPlace);
}
我收到以下错误:
warning LNK4006: "class std::basic_ostream > & __cdecl utils::operator<<(class std::basic_ostream > &,struct utils::astTime const &)" (??6utils@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV12@ABUastTime@0@@Z) already defined in Utils.obj; second definition ignored
最佳答案
您在代码中混合了声明和定义。将定义放入实现文件(*.cpp
)。将声明放入 header 中round
声明的旁边。
或者,您可以将定义放入 header 中并声明为 inline
(这对于诸如自定义运算符之类的短函数来说是常规的)。函数上的inline
说明符可防止函数在被多个翻译单元包含时违反One Definition Rule。
关于c++ - 在哪里声明结构运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60042762/