我正在编写一个非常简单的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;
};
Run Code Online (Sandbox Code Playgroud)
在我的主库文件Motor.cpp中,我有以下类构造函数:
Motor::Motor() {
// Intentionally do nothing.
}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用以下行在我的主程序中初始化我的类时:
Motor motor();
Run Code Online (Sandbox Code Playgroud)
我收到以下编译错误:
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()'
Run Code Online (Sandbox Code Playgroud)
令人困惑的部分是,如果我甚至包括垃圾,抛出的参数到Motor Class构造函数,如下所示:
class Motor
{
public:
Motor(int garbage);
...
Run Code Online (Sandbox Code Playgroud)
在.cpp文件中:
Motor::Motor(int garbage) { }
Run Code Online (Sandbox Code Playgroud)
在我的主文件中:
Motor motor(1);
Run Code Online (Sandbox Code Playgroud)
一切都完美无瑕.我已经通过Arduino论坛进行了相当多的搜索,但没有找到解释这种奇怪行为的内容.为什么类构造函数需要参数?这是一些奇怪的遗物绑在AVR或其他什么?
你遇到了"最令人烦恼的解析"问题(当然,因为它很烦人).
Motor motor();声明了一个函数称为motor不带参数,并返回Motor.(没有区别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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3223 次 |
| 最近记录: |