c++ - 为什么数组不能作为函数参数传递?

为什么不能将数组作为函数参数传递?

我一直在阅读这本 C++ 书籍,上面写着“你不能将数组作为函数参数传递”,但它从未解释过原因。此外,当我在网上查找时,我发现了诸如“你为什么要这样做?”之类的评论。不是我会做,我只是想知道你为什么做不到。

最佳答案

Why can't arrays be passed as function arguments?

他们可以:

void foo(const int (&myArray)[5]) {
   // `myArray` is the original array of five integers
}

在技术术语中,foo 的参数类型是“对 5 个 const ints 的数组的引用”;通过引用,我们可以在 周围传递 实际 对象(免责声明:术语因抽象级别而异)

你不能做的是按值传递,因为由于历史原因我们不会复制数组。相反,尝试将数组按值传递给函数(或者,传递数组的拷贝)会导致其名称衰减为指针。 (some resources get this wrong!)


数组名称衰减为按值传递的指针

这意味着:

void foo(int* ptr);

int ar[10]; // an array
foo(ar);    // automatically passing ptr to first element of ar (i.e. &ar[0])

还有一种极具误导性的“语法糖”,看起来就像您可以按值传递任意长度的数组:

void foo(int ptr[]);

int ar[10]; // an array
foo(ar);

但是,实际上,您仍然只是传递一个指针(指向 ar 的第一个元素)。 foo 和上面一样!

虽然我们正在这样做,但以下函数实际上并没有它看起来的签名。看看当我们尝试调用这个函数而不定义它时会发生什么:

void foo(int ar[5]);
int main() {
   int ar[5];
   foo(ar);
}

// error: undefined reference to `func(int*)'

所以foo实际上取int*不是 int[5]!

(Live demo.)


但你可以解决它!

You can hack around this 通过将数组包装在 structclass 中,因为默认的复制操作符复制数组:

struct Array_by_val
{
  int my_array[10];
};

void func (Array_by_val x) {}

int main() {
   Array_by_val x;
   func(x);
}

这有点令人困惑。


或者,更好的是通用的传递引用方法

在 C++ 中,借助一些模板魔法,我们可以使函数既可重用又能够接收数组:

template <typename T, size_t N>
void foo(const T (&myArray)[N]) {
   // `myArray` is the original array of N Ts
}

但是我们仍然不能通过值传递一个。需要记住的东西。


future ……

由于 C++11 刚刚问世,并且 C++0x 支持在主流工具链中得到很好的支持,您可以使用从 Boost 继承的可爱的 std::array!我将把研究留给读者作为练习。

https://stackoverflow.com/questions/7073194/

相关文章:

c++ - 访问另一个子类中基类的 protected 成员

c++ - 为什么 std::fstream 类不采用 std::string?

c++ - std::pair 的顺序是否明确?

c++ - 我不明白这个 C/C++ 笑话

c++ - 如何在 C++ 中将 unsigned char* 转换为 std::string?

c++ - 我收到错误 "invalid use of incomplete type ' 类映射'

C++ 异常 - 将 c-string 作为异常抛出是不是很糟糕?

c++ - 如何在编译时检查结构的大小?

c++ - OSX - 用通过 Homebrew 安装的 4.9 替换 gcc 版本 4.2.1

c++ - std::map 如何提供常量 size() 操作?