Я столкнулся с какой-то странной проблемой, я не знаю, как ее решить при перегрузке. Я пытаюсь перегрузить оператор ==. Простой пример:
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...
это легко и отлично работает, я пытаюсь обработать случай:
if (A==B==C==D)
поэтому мне нужно вернуть объект типа и теперь набрать bool. я попытался добавить еще одну функцию:
bla &bla:: operator==(const bool answer){//as a member function
if (answer)
return *this;
но, похоже, это не помогает. есть предложения? спасибо Stas
Это ужасная идея, и вы никогда не должны этого делать.
Вот как вы это делаете.
#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;
}
Этот код предполагает С++ 11, но может быть написан на С++ 98 с очень незначительными изменениями.
мне удалось найти другой подход, и он, похоже, отлично работает. спасибо to u all для вашей помощи и предложений.
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...
f
частным участником в этом случае. Кроме того, ваш код будет поврежден, если вы сделаете два сравнения подряд, а первое не получится.
bla A(1), B(2), C(1); if (A==B==C) int flag = 1; Ba=1; if (A==B==C) int flag=1;
ошибочно провалит второе сравнение.