c++ - 在类中创建对象
问题描述
我有这个问题:
问题:
- 我正在尝试创建一个管理和处理其他几个库(例如 WiFiServer 库)的库(ard33WiFi)
- 我需要创建服务器对象,然后在我的库 (ard33WiFi) 中的函数中使用它:
WiFiServer myServer(iPort);
- 问题是,当我在班级成员中调用 myServer 时,我得到:
'myServer' was not declared in this scope
我在哪里/如何声明 myServer 以便整个班级(ard33WiFi)都可以使用它?我已经取消了任何声明,因为无论我尝试什么都是错误的。我在下面粘贴了一个骨架代码。
// HEADER FILE (.h)
// ----------------------------------------------------------------------------------------------
#ifndef Ard33WiFi_h
#define Ard33WiFi_h
#include <WiFiNINA.h>
#include <WiFiUdp.h>
class ard33WiFi{
public:
ard33WiFi(int iPort)
void someFunction();
void serverBegin();
private:
int _iPort;
};
#endif
// ----------------------------------------------------------------------------------------------
// C++ FILE (.cpp)
// -----------------------------------------------------------------------------------------------
#include <Ard33Wifi.h>
ard33WiFi::ard33WiFi(int iPort){
_iPort = iPort;
}
void ard33WiFi::someFunction(){
// code here required to prepare the server for initializing
// but ultimately not relevant to the question
}
void ard33WiFi::serverBegin(){
myServer.begin();
Serial.println("Server Online");
}
我在 UDP 库中遇到了同样的问题,因为我需要在各种函数中调用 UDP 对象来做 UDP 事情。
任何帮助将不胜感激。
解决方案
我想你正在使用这个:
https://www.arduino.cc/en/Reference/WiFiServer
我可以看到您没有在课堂上声明 myServer ;我猜是你的代码中的错误。如果我没记错的话,应该是这样的:
#ifndef Ard33WiFi_h
#define Ard33WiFi_h
#include <WiFiNINA.h>
#include <WiFiUdp.h>
#include <WiFi.h> // Not sure if you have to append this include
class ard33WiFi{
public:
ard33WiFi(int iPort)
void someFunction();
void serverBegin();
private:
int _iPort;
WiFiServer myServer;
};
#endif
实现,您需要初始化实例:
#include <Ard33Wifi.h>
ard33WiFi::ard33WiFi(int iPort):myServer(iPort), _iPort(iPort) {
}
void ard33WiFi::someFunction(){
// code here required to prepare the server for initializing
// but ultimately not relevant to the question
}
void ard33WiFi::serverBegin(){
myServer.begin();
Serial.println("Server Online");
}
推荐阅读
- html - 使用html从外部源更改按钮的颜色?
- anychart - Anychart 缩放非地图图表类型
- javascript - 使用 React JavaScript 的 Spring-Boot
- android - onActivityResult 返回空数据
- python - Python绘图字典
- python - 一次访问多个索引行时有效地迭代 pandas.DataFrame
- javascript - 从 JsonConvert.SerializeObject(obj) 返回的 JSON 在 Json.parse 中返回“Unexpected token &”
- unity3d - GPGS Unity 插件 - 网络延迟检查和同步
- javascript - 为什么具有相同属性的两个对象不能以相同的方式工作
- wordpress - FacetWP 显示所有选项和方面