我有一个需要实现operator ==的类,它的返回类型是bool。我不确定代码是否正确实现它。
// MyTest.hpp文件
class Test {
public:
Test();
virtual ~Test();
int x,y;
bool operator==(const Test &v);
};
// MyTest.cpp file
bool Test::operator==(const Test &v) {
return (x== v.x) && (y==v.y);
}
即使代码编译是这种标准的实现方式,我们也需要使用模板。 我应该使用模板的实现方式,如下面的代码:
template <class T>
bool operator==(const T &v);
答案 0 :(得分:4)
除非您需要,否则不要使用模板。 Test
与任何类型相比是否有意义?我对此表示怀疑。
此外,没有&#34;标准方式&#34;因为标准没有强制实施operator==
的严格方法(我认为它提到了返回类型的东西,但我怀疑它实际上强制执行任何东西)。
最好让它返回bool
并让它完成人们期望它做的事情(以有意义的方式比较这两个对象)。
最后,您应该标记当前的const
:
bool operator==(const Test &v) const;
除非它实际修改了调用对象,这绝对是你不希望它做的事情。
答案 1 :(得分:1)
请不要使用匹配任何内容的模板:
template <class T>
bool operator==(const T &, const T &);
那会给你带来各种各样的麻烦!
答案 2 :(得分:1)
正如其他人所提到的,使用模板而没有任何理由这样做既不是标准也不是推荐。但是,如果您希望operator==
更像是默认比较运算符之一,则应标记为const
(否则您无法比较两个const Test
),如此
class Test {
public:
Test();
virtual ~Test();
int x,y;
bool operator==(const Test &v) const;
};
// MyTest.cpp file
bool Test::operator==(const Test &v) const {
return (x== v.x) && (y==v.y);
}
,或者使它成为一个自由函数(在ADL的同一名称空间中),取两个const Test &
(首选),如此
class Test {
public:
Test();
virtual ~Test();
int x,y;
};
bool operator==(const Test &a, const Test &b);
// MyTest.cpp file
bool operator==(const Test &a, const Test &b) {
return (a.x==b.x) && (a.y==b.y);
}
如果需要访问私人会员,则可以始终将自由功能标记为friend
。在简单的情况下,例如本例中的那个,在标题中进一步定义它并标记它inline
可能是有利的。