我在函數中使用各種參數進行初始化時遇到問題。如果我創建了一個數組,它就可以工作int params [] = {...}
。但是,如果我想將參數直接寫入函數中,則不起作用。
declaration
(在 .h 中)
void phase_an(int led[]);
in the .cpp
void RS_Schaltung::phase_an(int led[])
{
for (size_t i = 0; i < LEN(led); i++) {
digitalWrite(led[i], HIGH);
}
}
如果我嘗試這種方式,它將不起作用。我希望它是那樣的。但我在互聯網上找不到任何關於它的信息。...:in the Arduino sketch:
RS.phase_an(RS.ampelRot, RS.ampelGelb, ..... ); <--- is there a way to do it like that?
讓我驚訝的是它是這樣工作的:
int p_an [5] = {RS.ampelRot, RS.ampelGelb, RS.ampelGruen, RS.rot, RS.gelb};
...................
RS.phase_an (p_an);
有人有建議嗎?
有使函數接受可變數量的參數的幾種方法在這裡。
但是,在您當前的代碼中存在一個問題:當您將未知大小的本機數組作為函數的參數(例如void f(int a[])
)傳遞時,該參數將被管理為指向數組的指針,並且此函數內部無法知道該數組的實際長度。我不知道LEN()
是如何定義的,但它在您的代碼中運行不佳的可能性很高。
一個更安全、更實用的替代方法是使用 avector<int>
代替:
#include <iostream>
#include <vector>
using namespace std;
void f(const vector<int>& a){
for (int i=0; i<a.size(); i++) {
cout<<a[i]<<" ";
}
cout<<endl;
}
int main() {
vector<int> test={1,2,3,4};
f(test);
f({1,2,3,4});
return 0;
}
在這種情況下,您可以在函數調用中的括號之間傳遞多個值(例如({RS.ampelRot, RS.ampelGelb, RS.ampelGruen, RS.rot, RS.gelb})
,C++ 會自動將其轉換為向量。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句