2014-11-21 42 views
0

我基本上試圖初始化一個外部類,以便在我的所有方法中使用它作爲成員。從外部類創建成員

我的嘗試:

  • 初始化在頭文件中的成員(錯誤:error: 'RECV_PIN_1' is not a type
  • 在構造函數初始化它(現在是不是可以在我的方法)

這裏的我縮短的代碼:

// Receiver.h 
#include "Arduino.h" 
#include "IRremote.h" 

class Receiver { 
public: 
    Receiver(); 
    void tick(); 
private: 
    static const int LED_PIN = 13; 
    static const int RECV_PIN_1 = 11; 
    static const int MAX_HEALTH = 1000; 

    // [..] 

    IRrecv irrecv(RECV_PIN_1); // this does not work 

    // [..] 
}; 


// Receiver.cpp 
#include "Arduino.h" 
#include "IRremote.h" 
#include "Receiver.h" 

Receiver::Receiver() { 
    // [..] 
} 

void Receiver::tick() { 
    checkHitIndicator(); 
    // if there is a result 
    if (irrecv.decode(&results)) { 
     playerHitDetected(10); 
     // receive the next value 
     irrecv.resume(); 
    } 
} 

這會很好,如果somebod你可以解釋我是如何以及爲什麼會達到這個目標的。

回答

0

第一種方法只有在您的編譯器支持C++ 11類內初始化時纔有效;你需要={}初始化它,因爲初始化與()看起來太像一個函數聲明:

IRrecv irrecv{RECV_PIN_1}; // or 
IRrecv irrecv = IRecv(RECV_PIN_1); 

第二種方法應該罰款;我在類定義

IRecv irrecv; 

已經不知道爲什麼它可能不是在你的可用方法,只要你已經聲明它(不初始化),並在構造函數初始化它

Receiver::Receiver() : irrecv(RECV_PIN_1) { 
    // [..] 
} 
+0

嗨,我的編譯器不支持第一種方法。 第二個拋出一個神祕的錯誤'未定義的引用'IRrecv :: IRrecv(int)'' – 2014-11-21 10:18:21

+0

@JulianHollmann:第二個應該是,這是從時間的黎明以來的標準。 – 2014-11-21 10:18:56

+0

我更新了我的評論,第二種方法也不適用於我 – 2014-11-21 10:20:44