提问者:小点点

重载的less then运算符返回相反的布尔值


我重载了booking类中的less then运算符。

#include <iostream>
using namespace std;

class Booking{

private:
long bookingID;

public:
Booking(long bookingID) : bookingID(bookingID){}
long getBookingID(){
    return bookingID;
}

bool operator<(Booking &b){
    return this->bookingID<b.getBookingID();
}
}



int main(){
  Booking* b2 = new Booking(11);
  Booking* b1 = new Booking(2);

  cout << (b1<b2) << endl; // returns 0 (expected 1)
  cout << (b2<b1) << endl; // returns 1 (expected 0)

  return 0;
}

问题是什么? 还是我误会了什么?


共1个答案

匿名用户

您正在比较指针,而不是对象。

你的意思是:

Booking b2( 11);
Booking b1( 2);

cout << (b1<b2) << endl; // returns 1, as expected
cout << (b2<b1) << endl; // returns 0, as expected