我是C ++的初学者。所以请耐心等待:
我尝试为温度传感器编写代码,该代码应将值发布到API。
我无法实例化我的班级ApiClient
。我总是得到这些错误:
我的代码看起来像这样(稍微修一下以便于阅读):
main.cpp中
#include <ApiClient.h>
ApiClient api;
void setup()
{
Serial.begin(115200);
String apiUrl = "https://myapi.com/api";
api(apiUrl); // ERROR: raises call of an object of a class type without appropriate operator() or conversion functions to pointer-to-function type
}
void loop()
{
String temp = "49";
api.sendValue("temperature", temp);
}
ApiClient.h
#ifndef WebClient_h
#define WebClient_h
#include <Arduino.h>
#include <WiFi.h>
#include <esp_wps.h>
#include <HTTPClient.h>
class ApiClient
{
public:
ApiClient(); // this is only added for testing
ApiClient(String apiUrl); // it should always instanciate with url
void sendValue(String key, String value);
String _apiUrl;
private:
};
#endif
ApiClient.cpp
#include <ApiClient.h>
String _apiUrl;
HTTPClient http;
ApiClient::ApiClient(String apiUrl) // IDE says: "no instance of overloaded function "ApiClient::ApiClient" matches the specified type"
{
this->_apiUrl = apiUrl;
// some stuff to establish a connection
}
您正在尝试在已构造的对象上调用构造函数。
此行失败:
api(apiUrl);
您尝试的调用失败,因为编译器正在寻找以下函数之一:
return_type APIClient::operator()(const String&);
return_type APIClient::operator()(String);
return_type APIClient::operator()(String&);
如果您希望调用构造函数,则您的语句应该是声明。
ApiClient api(apiUrl);
// or better in c++11:
APIClient api{ apiUrl };
或者,您可以在ApiClient中创建一个初始化程序,它将一个String作为参数,如下所示:
class ApiClient
{
public:
ApiClient() { ...}
ApiClient(const String& s) { Initialize(s); }
Initialize(const String& s) { do the work }
...
};
在类中提供一步和两步初始化API时要小心。您需要一个正确的重置功能,以避免在使用新字符串重新初始化时混淆。