gpt4 book ai didi

c++ - 无效的构造函数 token C++ Arduino

转载 作者:搜寻专家 更新时间:2023-10-31 01:39:40 24 4
gpt4 key购买 nike

我遇到了错误

C:\Users\Jake\Documents\Arduino\libraries\Sonar\Sonar.cpp:3:13: error: expected >constructor, destructor, or type conversion before '(' token Sonar::Sonar(trigLeft,echoLeft,trigRight, echoRight) Error compiling.

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

声纳.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;
}

声纳.h:

#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) {
}

这是唯一的方法。

关于c++ - 无效的构造函数 token C++ Arduino,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30855330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com