Arduino C++无效的构造函数令牌

Invalid constructor token C++ Arduino

本文关键字:构造函数 令牌 无效 C++ Arduino      更新时间:2023-10-16

我收到错误

C:\Users\Jake\Documents\Arduino\libraries\Sonar\Sonar.cpp:3:13:错误:预期>构造函数、析构函数或类型转换在"("标记之前 声纳::声纳(左三角,左回声,右三角,右回声) 编译时出错。

我不知道是什么原因造成的,有一次缺少一个大括号,但我重新添加了它。代码如下

声纳.cpp:

#include "Sonar.h"
Sonar::Sonar(trigLeft,echoLeft,trigRight, echoRight) {
    pinMode(triggerPinLeft,OUTPUT);
    pinMode(triggerPinRight,OUTPUT);
    pinMode(echoPinLeft,INPUT);
    pinMode(echoPinRight,INPUT);
    triggerPinLeft = trigLeft;
    echoPinLeft = echoRight;
    triggerPinRight = trigRight;
    echoPinRight = echoRight;
}

void Sonar::Ping() {
  digitalWrite(triggerPinLeft, LOW);
  digitalWrite(triggerPinRight, LOW);
  delayMicroseconds(2);
  digitalWrite(triggerPinLeft, HIGH);
  digitalWrite(triggerPinRight, HIGH);;
  delayMicroseconds(5);
  digitalWrite(triggerPinLeft, LOW);
  digitalWrite(triggerPinRight, LOW);
  // Read EchoPins
  long durationLeft = pulseIn(echoPinLeft, HIGH);
  long durationRight = pulseIn(echoPinRight, HIGH);
  // convert the time into a distance
  cmLeft = microsecondsToCentimeters(durationLeft);
  cmRight - microsecondsToCentimeters(durationRight);
  delay(100);
}
long Sonar::microsecondsToCentimeters(long microseconds) {
    // The speed of sound is 340 m/s or 29 microseconds per centimeter.
    return microseconds / 58;
}

声纳:

#ifndef Sonar_h
#define Sonar_h
#include "Arduino.h"
class Sonar {
  public:
    Sonar(int,int,int,int);
    long cmLeft,cmRight;
    void Ping();
  private:
    const int triggerPinLeft,echoPinLeft,triggerPinRight,echoPinRight;
    long microsecondsToInches(long microseconds);
    long microsecondsToCentimeters(long microseconds);
};
#endif

最后是Sonar.ino(这是针对Arduino的,我相信它工作正常)

#include <Sonar.h>
Sonar sonar(20,21,22,23);
void setup() {
// put your setup code here, to run once:
}
void loop() {
  // put your main code here, to run repeatedly:
  sonar.Ping();
  long sonarLeftDistance = sonar.cmLeft;
  long sonarRightDistance = sonar.cmRight;
}

这就是所有代码。Arduino位在很大程度上是无关紧要的。

您错过了根据构造函数声明在函数定义中指定参数类型:

Sonar(int,int,int,int); // Declaration

Sonar::Sonar(int trigLeft, int echoLeft, int trigRight, int echoRight) {
          // ^^^           ^^^           ^^^            ^^^
    // ...
}

由于相应的类成员变量声明为 const

    const int triggerPinLeft,echoPinLeft,triggerPinRight,echoPinRight;
 // ^^^^^  

它们需要使用构造函数成员初始值设定项列表进行初始化:

Sonar::Sonar(int trigLeft, int echoLeft, int trigRight, int echoRight) 
: triggerPinLeft(trigLeft)
, echoPinLeft(echoLeft)
, triggerPinRight(trigRight)
, echoPinRight(echoRight) {
}

这是你能做到的唯一方法。

相关文章: