当short int []自动转换为long int []时会发生什么?

And*_*rew 0 c++ arrays casting

在C++中,如果我有一个短整数数组并将其作为参数传递给一个采用长整数数组的函数,那么函数是否会将short数组的每个值转换为long int或整个数组将被重新解释成为一个由n/2个元素组成的长整数?

Jam*_*lis 5

你不能,因为没有可以使用的自动演员表.

请记住,您不能通过值将数组传递给函数:数组参数实际上只是一个指针参数,因此以下两个是相同的:

void f(long a[]);
void f(long* a);
Run Code Online (Sandbox Code Playgroud)

将数组传递给函数时,数组会隐式转换为指向其初始元素的指针.所以,鉴于long data[10];,以下两个是相同的:

f(data);
f(&data[0]);
Run Code Online (Sandbox Code Playgroud)

没有来自隐式转换short*long*,所以如果data被声明为short data[10];,你会得到一个编译错误.

您需要显式地转换short*为a long*,using reinterpret_cast,但不会将"N个short元素的数组"转换为"N个long元素的数组",它会将指向的数据重新解释为"[某个数字的数组] ]的long元素,"这可能不是你想要的.

您需要创建一个新的long元素数组,并将数组中的元素复制short到以下数组中long:

short data[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

long data_as_long[10];
std::copy(data, data + 10, data_as_long);
f(data_as_long);
Run Code Online (Sandbox Code Playgroud)

或者,您可以考虑将您的函数更改为可以接受指向任何类型元素的数组的指针的模板:

template <typename T> void f(T*);
Run Code Online (Sandbox Code Playgroud)

或者,对于更高级的解决方案,最常用的方法是让您的函数采用迭代器范围.这样,你可以传递任何类型的迭代器(包括指向数组的指针).此外,它提供了一种自然而简单的方法来确保正确传递数组的长度,因为长度未明确传递,它由参数决定.

template <typename Iterator> void f(Iterator first, Iterator last);

const unsigned length_of_data = 10;
long data_array[length_of_data];
std::vector<long> data_vector(length_of_data);

f(data_array, data_array + length_of_data); // works!
f(data_vector.begin(), data_vector.end());  // also works!
Run Code Online (Sandbox Code Playgroud)