c++ - 如何设置 float* 参数的默认值,它应该是指向数组的指针

标签 c++

我正在尝试为 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/

相关文章:

c++ - 如何监控 FIFO 的读取和写入?

c++ - OpenCV 3.0中findEssentialMat函数的使用

c++ - 为什么将 `istream&` 取到临时 `stringstream` 工作,但取 `stringstream&` 时不起作用?

c++ - 如何将 wchar[260] 和 wchar_t 转换为 const char *

c++ - 垂直和水平缩放 Gtkmm 小部件

python - 将 boost::python::object 转换为(非常量)左值

c++ - 无法为 Typedef 声明好友

c++ - Qt 秒到 DD HH SS

c++ - std::map 标准分配器性能与 block 分配器

c++ - 在 makefile 之外运行应用程序时出现段错误