为什么我的Arduino类构造函数需要参数?

时间:2015-12-09 03:16:36

标签: c++ arduino avr

我正在写一个非常简单的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或其他东西绑在一起吗?

2 个答案:

答案 0 :(得分:9)

你遇到了“最令人烦恼的解析”问题(当然,这个问题因为它很烦人)。

Motor motor();声明一个名为motor函数,它不带任何参数并返回Motor。 (与int test();或类似的没有区别)

要定义名为Motor的{​​{1}}的实例,请使用不带括号的motor

答案 1 :(得分:5)

作为接受答案的补充:

从C ++ 11开始,您可以使用“统一初始化”语法。在函数形式上统一初始化的一个优点是,大括号不能与函数声明相混淆,这种情况发生在你的情况下。 除了使用大括号 {} 之外,语法可以像功能语法一样使用。

有一些很好的例子over here

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