在类中创建对象
Creating object(s) within a Class
本文关键字:创建对象 更新时间:2023-10-16
我有这个问题:
问题:
- 我正在尝试创建一个库(ard33WiFi(来管理和处理其他几个库(例如WiFiServer库(
- 我需要创建服务器对象,然后在我的库(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");
}
相关文章:
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何创建对象函数指针C++映射?
- C++创建对象数组
- 在 C++ 的 Switch Case 中创建对象后对对象调用方法
- 如何获取在 main() 函数中构造的类的创建对象?
- 基于文件中的条目创建对象
- 错误:创建对象后无法分配区域
- C++ 通过输入创建对象
- 堆还是堆栈用于创建对象?
- 使用 C++ 创建对象数组
- 使用unique_ptr创建对象
- C++递归地在类构造函数中创建对象
- 通过向构造函数其他对象引用页面来创建对象
- ReactiveX (rx) - 在对象上应用可观察对象,而不是在可观察对象中创建对象
- 如何在OSX上正确创建C++对象文件(.o)
- 编译器是否会创建vtable,而不考虑在c++中创建对象
- 创建对象并防止被破坏
- 在C++中,友元类可以从友元类创建对象吗
- 只在堆中创建C++对象
- 创建用户定义的复制构造函数时无法创建对象