[英]operator overloading c++ (x==y==z)
I have encountered a strange problem, that I don't know how to solve in overloading. 我遇到了一个奇怪的问题,我不知道如何解决重载。 Im trying too overload operator == .
我正在尝试重载运算符==。 The easy example would be:
一个简单的例子是:
class bla{
public:
int a;
void bla(int a):a(a){}//costructor
bool operator==(const bla& ob)
return (a==ob.a);//chk if equal
};
void main(){
bla A,B;
if (A==B)
flag=1;//just an example...
this is easy and works great, i'm trying to handle the case of: 这很容易并且效果很好,我正在尝试处理以下情况:
if (A==B==C==D)
so i need to return type object and now type bool. 所以我需要返回类型对象,现在键入布尔。 i have tried to add another function :
我试图添加另一个功能:
bla &bla:: operator==(const bool answer){//as a member function
if (answer)
return *this;
but it doesn't seem to help. 但这似乎没有帮助。 have any suggestions?
有什么建议吗? thx Stas
斯塔斯
This is a horrible idea and you should never do it. 这是一个可怕的主意,您永远不要这样做。
Here is how you do it. 这是您的操作方式。
#include <type_traits>
template<typename T, typename U>
struct decay_equiv
: std::is_same<
typename std::decay<T>::type,
typename std::decay<U>::type
>::type {};
template<typename T>
struct comparator {
bool res;
T passalong;
explicit operator bool() { return res; }
typename std::enable_if<
!decay_equiv<T, comparator<T> >::value,
comparator<T>
>::type operator==(T const& rhs);
comparator<T> operator==(comparator<T> const& rhs);
};
template<typename T>
typename std::enable_if<
!decay_equiv<T, comparator<T>>::value,
comparator<T>
>::type comparator<T>::operator==(T const& rhs) {
if (!res) {
return {res, rhs};
}
return {(passalong == rhs).res, rhs};
}
template<typename T>
comparator<T> comparator<T>::operator==(comparator<T> const& rhs) {
if (!res || !rhs.res) {
return {res, rhs};
}
return {(passalong == rhs.passalong).res, rhs.passalong};
}
struct bla {
int a;
comparator<bla> operator==(bla const& rhs);
comparator<bla> operator==(comparator<bla> const& rhs);
};
comparator<bla> bla::operator==(bla const& rhs) {
return {a == rhs.a, rhs};
}
comparator<bla> bla::operator==(comparator<bla> const& rhs) {
if (!rhs.res) {
return rhs;
}
return {a == rhs.passalong.a, rhs.passalong};
}
int main() {
bla a = {0},b = {0},d = {0};
if (a==b==d)
return 0;
return -1;
}
This code assumes C++11, but can be written in C++98 with only very minor changes. 该代码假定使用C ++ 11,但只需很小的改动就可以用C ++ 98编写。
i have managed to find a different approach and it seems to work great. 我设法找到一种不同的方法,它似乎很好。 thx to u all for your help and suggestions.
非常感谢您的帮助和建议。
class bla{
public:
int a;
bool f;
void bla(int a):a(a){f = true;}//costructor
operator bool(){return f};
bla& operator==(const bla &ob){//chk if equal
if (f)
f=(a==ob.a);
return *this;
}
};
void main(){
bla A(4),B(4),C(4),D(4);
if (A==B==C==D)
flag=1;//just an example...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.