2015-11-15 25 views
-3

有可能與C++做下面的代碼:可以在C++中爲函數內的數組分配一個Int值?

myFunction(myArray, positionInsideMyArray) = myValue. 
cout << myFunction[positionInsideMyArray] << endl; // Display muValue 

我如何能做到這一點與C++?

爲了讓我的問題更清楚,使用一個值以下代碼可以正常工作, 我想要做同樣的事情,但使用Array參數。

int& myFunction(int &x){ 
return x; 
} 

這是主要的功能:

int x; 
myFunction(x) = myValue; 
cout << x << endl; // This will display myValue 
+2

您可以在C++中使用重載的運算符函數執行各種瘋狂的事情。你需要爲你的問題提供更多的上下文。請發佈[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 –

+0

是的。你可以用C++做所有這些事情,使用'operator()'重載和'operator []'重載。 – Mykola

+0

@Yacino只需搜索「C++將數組傳遞給函數」。 – LogicStuff

回答

1
#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]; 
} 
+0

這正是我想要的,謝謝:D – Yacino

+1

@Yacino但是你知道這不是你問的嗎? ...請爲你的下一個問題,請注意你的代碼示例。顯然,你會看到與你想要的完全不同的東西。而那些準確回答你問題的人浪費了他們的時間。 – deviantfan

0
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;