2013-08-18 9 views
1

我試圖創建在C++一個簡單的類,但我不斷收到編譯錯誤:類函數(Arduino的)的參數不編譯

main:2: error: variable or field 'doSomething' declared void 
main:2: error: 'person' was not declared in this scope 

主:

class person { 
    public: 
    int a; 
}; 

void doSomething(person joe) { 
    return; 
} 

主()和東西會在這裏,但即使我包含main(){},錯誤仍然會發生。我也嘗試添加2右括號喬之後,但隨後即創建錯誤:

main: In function 'void doSomething(person (*)())': 
main:8: error: request for member 'a' in 'joe', which is of non-class type 'person (*)()' 

任何幫助是極大的讚賞。 (我希望這不是我真的很愚蠢,因爲我一直在研究幾個小時)。

編輯:我發現這是一個Arduino特定的錯誤。 This post解答它。

+0

你的代碼中還有一個名爲'person()'的函數嗎? –

+3

你的代碼編譯正確,所以一定有其他東西http://ideone.com/QpdPka –

+0

不,我沒有在這段代碼中的任何其他功能。這是我唯一擁有的東西。 –

回答

2

我發現讀this post後一種方式來解決,這是:

typedef struct person{ 
public: 
    int a; 
}; 

void doSomething(void *ptr) 
{ 
    person *x; 
    joe = (person *)ptr; 
    joe->a = 3; //To set a to 3 
    //Everything else is normal, except changing any value of person uses "->" rather than "." 

    return; 
} 

main() 
{ 
    person larry; 
    doSomething(&larry); 
} 

所以基本上它是:

- 改變classtypedef struct

-in參數,更換新型與void *something

-add person *x; and x = (person *)ptr;的功能

-whenever訪問類型屬性的開始,使用->而不是.

+1

這似乎是一個巨大的混亂,解決什麼必須是一個有問題的IDE /編譯器。 –

0

我的猜測是,在「class person ...」上面的聲明中,有一個無效的語法錯誤。你能複製並粘貼整個文件嗎?

+0

這是整個文件,但我發現什麼是錯誤的,現在我知道它是arduino特定的。 –

1

我不是專家,但是當我試着去做自己想做的事,我做這種方式:

//create an instance of my class 
MyAwesomeClass myObject; 

void myFunction(MyAwesomeClass& object){ 
    //do what you want here using "object" 
    object.doSomething(); 
    object.doSomethingElse(); 
} 

void setup() { 
    //setup stuff here 
    myObject.init(); 
} 

void loop() { 
    //call myFunction this way 
    myFunction(myObject); 
} 

正如我所說,我不是一個C++專家,但它的工作。 希望它有幫助!

相關問題