簡體   English   中英

為什么我的Arduino類構造函數需要參數?

[英]Why does my Arduino Class Constructor require an argument?

我正在編寫一個非常簡單的Arduino類來控制兩個電機。

我的頭文件Motor.h中有一個簡單的類定義:

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.cpp中,我有以下類構造函數:

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

當我嘗試使用以下行在我的主程序中初始化我的類時:

Motor motor();

我收到以下編譯錯誤:

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 Class構造函數,如下所示:

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

在.cpp文件中:

Motor::Motor(int garbage) { }

在我的主文件中:

Motor motor(1);

一切都完美無瑕。 我已經通過Arduino論壇進行了相當多的搜索,但沒有找到解釋這種奇怪行為的內容。 為什么類構造函數需要參數? 這是一些奇怪的遺物綁在AVR或其他什么?

你遇到了“最令人煩惱的解析”問題(當然,因為它很煩人)。

Motor motor(); 聲明一個名為motor函數 ,它不帶參數並返回一個Motor (與int test();沒有區別int test();或類似)

要定義一個實例的Motor稱為motor ,使用Motor motor; 沒有括號。

作為接受的答案的補充:

從C ++ 11開始,您可以使用“統一初始化”語法。 在函數形式上統一初始化的一個優點是,大括號不能與函數聲明相混淆,這種情況發生在你的情況下。 除了使用大括號{}之外,語法可以像功能語法一樣使用。

有一些很好的例子在這里

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM