gpt4 book ai didi

c++ - 运算符重载 c++ (x==y==z)

转载 作者:行者123 更新时间:2023-11-28 06:32:16 25 4
gpt4 key购买 nike

我遇到了一个奇怪的问题,我不知道如何解决重载问题。我也在尝试重载运算符 == 。简单的例子是:

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;

但好像没什么用。有什么建议吗?谢谢斯塔斯

最佳答案

这是一个可怕的想法,你永远不应该这样做。

这是你如何做的。

#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;
}

此代码假定使用 C++11,但只需稍作改动即可用 C++98 编写。

关于c++ - 运算符重载 c++ (x==y==z),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27334050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com