在C++中,可以将Int值分配给函数内部的数组
It is possible to assign an Int value to an Array inside a Function in C++?
使用C++可以执行以下代码:
myFunction(myArray, positionInsideMyArray) = myValue.
cout << myFunction[positionInsideMyArray] << endl; // Display muValue
我如何用C++做到这一点?
为了让我的问题更清楚,使用一个值,以下代码可以正确工作,我想做同样的事情,但使用数组参数。
int& myFunction(int &x){
return x;
}
这是主要功能:
int x;
myFunction(x) = myValue;
cout << x << endl; // This will display myValue
#include <iostream>
int &myFunction(int *arr, size_t pos) { return arr[pos]; }
int main() {
using std::cout;
int myArray[30];
size_t positionInsideMyArray = 5;
myFunction(myArray, positionInsideMyArray) = 17.;
cout << myArray[positionInsideMyArray] << "n"; // Display muValue
}
或带有错误检查:
#include <stdexcept>
template<size_t N>
inline int &myFunction(int (&arr)[N], size_t pos)
{
if (pos >= N)
throw std::runtime_error("Index out of bounds");
return arr[pos];
}
myFunction(myArray, positionInsideMyArray) = myValue.
cout << myFunction[positionInsideMyArray] << endl;
仅凭函数,第二行是不可能的;你需要上课
但是,第二个调用会记住
中的myArray
首先让整个语义有点奇怪
一个粗略的想法(没有完整的类,只适用于int数组):
class TheFunc
{
int *arr;
int &operator() (int *arr, size_t pos)
{
this->arr = arr;
return arr[pos];
}
int &operator[] (size_t pos)
{
return arr[pos];
}
};
...
TheFunc myFunction;
myFunction(myArray, positionInsideMyArray) = myValue.
cout << myFunction[positionInsideMyArray] << endl;
一个不同的、更健壮的版本,其中它单独设置的阵列:
class TheFunc
{
int *arr;
TheFunc(int *arr)
{
this->arr = arr;
}
int &operator() (size_t pos)
{
return arr[pos];
}
int &operator[] (size_t pos)
{
return arr[pos];
}
};
...
TheFunc myFunction(myArray);
myFunction(positionInsideMyArray) = myValue.
cout << myFunction[positionInsideMyArray] << endl;
相关文章:
- 无法分配函数指针的 2D 数组
- Clang-Format 不能正确分配函数参数
- 我们可以在cpp中为对象分配函数吗
- 分段错误分配函数结果
- 在类内分配函数指针
- 创建一个移动分配函数,不断得到"pointer being freed was not allocated"
- 如何在C++中重新分配函数名称
- 尝试分配函数指针时获取"Void value not ignored as it ought to be"
- 尝试从文件中获取数据时,在C 中的分配函数中没有正确的字符串
- 当使用内存分配函数用作条件语句时会发生什么
- 解除分配函数的 A 函数 B 内的运行时内存
- 是否可以编写一个自定义 STL 分配器,该分配器使用指向用户提供的分配函数的指针
- 当分配函数指针时,这两种符号之间有什么区别
- 新的运算符分配函数顺序连续性和初始值
- 在类中分配函数指针会在C++中给出值类型错误
- 函数包装中的堆栈分配/函数中的alloca
- 创建线程,在循环中为其分配函数并执行
- 我想我可以理解 N5.3.4 中的 §4140/11,但已扩展的分配函数的概念对我来说是不可理解的
- 析构函数和解分配函数的区别是什么?
- 为什么分配函数使用std::nothrow_t作为引用而不是值