Type Operator Overloading in C++

C++ has a powerful mechanism for operator overloading. Beside operator such as
+, -, =, ==, type name can also be overloaded as operator. Here is an example. 
It allows Device to be implicitly converted into DeviceHandle.

 

class DeviceHandle {
};

class Device {
  public:
    Device(DeviceHandle dh) : _dh(dh) {
    }
    operator DeviceHandle() const {
      return _dh;
    }
  private:
    DeviceHandle _dh;
};

void updateDeviceHandle(DeviceHandle dh) {
}

int main(int argc, const char *argv[]) {
  DeviceHandle dh1;
  Device d1(dh1);
  updateDeviceHandle(d1);
  return 0;
}
 

你可能感兴趣的:(C++,c,C#)