gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:24:35 24 4
gpt4 key购买 nike

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

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;
}

最佳答案

构造函数 explicit :

explicit Point(float value) : value(value) {} // no semicolon here

这不允许隐式转换(从 size_tfloatPoint),但请注意,它也会使代码如 start .distanceTo(3.14)Point p = 3.14; 无效。

关于c++ - 如何防止 size_t 被解释为引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38040356/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com