我正在尝试为 float* (C++) 设置一个默认值 作为函数参数。 例如-
Foo(float* x = (a default value should be {0,250}))
有人知道怎么做吗?
最佳答案
由于 x
是一个指针,您不能为其设置默认数值。您只能设置一个默认地址。要模拟给它一个默认值,在某处有一个常量 float
(或者在本例中是一个 float[2]
)并使 x
> 默认为它。
const float default_x[2] = { 0.f, 250.f };
void foo(const float * x = default_x) {
// use x
}
请注意,使用 C 风格的数组很容易出错,在现代 C++ 代码中不推荐使用。相反,更喜欢 std::array
当编译时已知大小或 std::vector
否则。例如,下面的代码将获得类似的结果并且使用起来更安全:
#include <array>
const std::array<float, 2> default_x = { 0.f, 250.f };
void foo(const std::array<float, 2> & x = default_x) {
// use x
}
关于c++ - 如何设置 float* 参数的默认值,它应该是指向数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53323676/