我最近正在处理一些代码,并决定在 C++ 中处理我的运算符重载,因为我以前从未真正实现过它。因此,我使用比较函数重载了矩阵类的比较运算符,如果 LHS 小于 RHS,则返回 0,如果 LHS 大于 RHS,则返回 1,如果它们相等,则返回 2。然后我在整数上利用了逻辑不在 c++ 中的属性,将我所有的比较放在一行中:
inline bool Matrix::operator<(Matrix &RHS){
return ! (compare(*this,RHS));
}
inline bool Matrix::operator>(Matrix &RHS){
return ! (compare((*this),RHS)-1);
}
inline bool Matrix::operator>=(Matrix &RHS){
return compare((*this),RHS);
}
inline bool Matrix::operator<=(Matrix &RHS){
return compare((*this),RHS)-1;
}
inline bool Matrix::operator!=(Matrix &RHS){
return compare((*this),RHS)-2;
}
inline bool Matrix::operator==(Matrix &RHS){
return !(compare((*this),RHS)-2);
}
显然我应该将 RHS 作为 const 传递,我可能不会再使用这个矩阵类,而且我不想编写另一个不是引用的函数来单独获取数组索引值比较器操作。
根据建议,如果比较返回 -1 表示小于,0 表示相等,1 表示正,则代码如下。
inline bool Matrix::operator<(Matrix &RHS){
return ! (compare(*this,RHS)+1);
}
inline bool Matrix::operator>(Matrix &RHS){
return ! (compare((*this),RHS)-1);
}
inline bool Matrix::operator>=(Matrix &RHS){
return compare((*this),RHS)+1;
}
inline bool Matrix::operator<=(Matrix &RHS){
return compare((*this),RHS)-1;
}
inline bool Matrix::operator!=(Matrix &RHS){
return compare((*this),RHS);
}
inline bool Matrix::operator==(Matrix &RHS){
return !(compare((*this),RHS));
}
我不知道这是否真的增加了可读性。
最佳答案
是的,它太聪明了——我读了这段代码,不得不考虑为什么你要从一个名为 compare
的函数中减去两个。不要让我思考。
如果您很聪明地将代码放在一行上,那么您的优先级就会困惑。您应该使用尽可能多的行来使您的代码尽可能清晰。
Programs must be written for people to read, and only incidentally for machines to execute. (Abelson & Sussman, Structure and Interpretation of Computer Programs)
关于c++ - 这是否过于聪明或不安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2845372/