gpt4 book ai didi

c++ - 在类中创建对象

转载 作者:行者123 更新时间:2023-11-27 23:36:57 25 4
gpt4 key购买 nike

我有这个问题:

问题:

  • 我正在尝试创建一个库 (ard33WiFi) 来管理和处理一些其他库(例如 WiFiServer 库)
  • 我需要创建服务器对象,然后在我的库 (ard33WiFi) 中的函数中使用该对象:

WiFiServer myServer(iPort);

  • 问题是,当我在类的成员中调用 myServer 时,我得到:

'myServer' 未在此范围内声明

我在哪里/如何声明 myServer 以便它对整个类(class) (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++ - 在类中创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58567082/

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