struct nodo{
int v,k,dist;
nodo(){
}
nodo(int _v, int _k, int _dist){
v=_v;
k=_k;
dist=_dist;
}
bool operator < (nodo X) const{
return dist>X.dist;
}
}
我正在尝试理解这段代码。但我没有得到 bool 运算符部分。
“return dist>X.dist”是什么意思? 如果 dist 大于 X.dist,返回 true?
最佳答案
what does mean by "return dist>X.dist"? If dist is bigger than X.dist, return true?
你是对的。
运算符与普通成员函数没有什么不同。编译器只在找到该运算符时执行该函数。
你可以试着写一个打印语句,看看会发生什么
bool operator < (nodo X) const{
std::cout << "Operator < called" << std::endl;
return dist < X.dist; // I changed the sign because it looks more natural
}
// ...
int main() {
nodo smallnode(1,2,3);
nodo bignode(4,5,6);
std::cout << "First node Vs Second Node" << std::endl;
if (smallnode < bignode)
std::cout << "It's smaller!" << std::endl;
else
std::cout << "It's bigger!" << std::endl;
}
关于c++ - 我没有得到运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43028065/