在C++中,可以将Int值分配给函数内部的数组

It is possible to assign an Int value to an Array inside a Function in C++?

本文关键字:分配 函数 内部 数组 Int C++      更新时间:2023-10-16

使用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;