如何防止size_t被解释为引用?

Vis*_*orZ 2 c++ constructor class implicit-conversion

如何distanceTo(..)使用std::size_tas参数更改签名以使编译器在调用时发出警告或错误?

class Point {
private:
  float value;

public:
  Point(float value) : value(value){};
  float distanceTo(const Point &point) { return point.value - value; }
};

int main() {

  std::size_t index = 1;
  Point start(1);
  Point end(4);
  float dist = start.distanceTo(index); // compiles, but should not!
  std::cout << dist;

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

Log*_*uff 13

制作构造函数explicit:

explicit Point(float value) : value(value) {} // no semicolon here
Run Code Online (Sandbox Code Playgroud)

这不允许隐式转换(从size_t通过floatPoint),但要注意,这也让这样的代码start.distanceTo(3.14)Point p = 3.14;无效的.