2015-12-09 2 views
5

私は2つのモーターを制御する非常にシンプルなArduinoクラスを書いています。Arduino Class Constructorに引数が必要なのはなぜですか?

私は私のヘッダファイルMotor.h内部の簡単なクラス定義があります。私のメインのライブラリファイル、Motor.cppで

class Motor 
{ 
    public: 
    Motor(); 
    void left(int speed); 
    void right(int speed); 
    void setupRight(int rightSpeed_pin, int rightDirection_pin); 
    void setupLeft(int leftSpeed_pin, int leftDirection_pin); 
    private: 
    int _rightMotorSpeedPin; 
    int _rightMotorDirectionPin; 
    int _leftMotorSpeedPin; 
    int _leftMotorDirectionPin; 
}; 

を、私は以下のクラスのコンストラクタを持っている:

Motor::Motor() { 
    // Intentionally do nothing. 
} 

私はラインで私の主なプログラムの中で私のクラスを初期化しよう:

私は、次の取得しますコンパイルエラー:

class Motor 
{ 
    public: 
     Motor(int garbage); 
     ... 

そして、.cppファイル内:

Motor::Motor(int garbage) { } 

MotorClassExample.ino: In function 'void setup()': 
MotorClassExample:7: error: request for member 'setupRight' in 'motor', which is of non-class type 'Motor()' 
MotorClassExample:8: error: request for member 'setupLeft' in 'motor', which is of non-class type 'Motor()' 
request for member 'setupRight' in 'motor', which is of non-class type 'Motor()' 

不可解な部分があれば、私はこのようなモータークラスのコンストラクタにも、ごみ、使い捨ての引数が含まれていることです

そして、私のメインのファイルに:

Motor motor(1); 

すべてが苦情なしで完璧に動作します。私はArduinoのフォーラムを通してかなりの調査をしましたが、この奇妙な行動を説明するものは何も見つかりませんでした。なぜクラスコンストラクタは引数を必要としますか?これはAVRや何かにつながっている奇妙な遺物ですか?

答えて

8

あなたは "厄介な解析"という問題に遭遇しました。

Motor motor();は引数を取らず、Motorを返しmotor呼ば機能を宣言します。 (いいえint test();異なるまたは類似の)

はない括弧でMotor motor;を使用し、motor呼ばMotorのインスタンスを定義します。 C++ 11あなたは「均一な初期化」構文を使用することができますので、

:受け入れ答えに加えとして

+0

があります。奇妙なバグ。ありがとう、トン。 –

3

。関数型よりも一様な初期化の利点は、中括弧を関数宣言と混同することができないことです。 構文は機能的なものと同じように使用できますが、中括弧{}を使用する点が異なります。

いくつかの良い例があなたはとてもハードロックover here

Rectangle rectb; // default constructor called 
Rectangle rectc(); // function declaration (default constructor NOT called) 
Rectangle rectd{}; // default constructor called 
+0

チップをありがとう。それは有り難いです。 –

関連する問題