错误:非静态引用成员,无法使用默认的赋值运算符

3

我正在将一个现有库("Webduino",用于Arduino的Web服务器)适配到另一个现有库("WiFly",一种wifi模块),但遇到了问题。每个库单独运行都很好。Webduino库希望通过SPI使用以太网硬件模块,而WiFi模块则使用串口(UART)。我收到的错误信息是:

WiFlyClient.h: In member function 'WiFlyClient& WiFlyClient::operator=(const WiFlyClient&)':
WiFlyClient.h:14:
error: non-static reference member 'WiFlyDevice& WiFlyClient::_WiFly', can't use default assignment operator
WiFlyWebServer.h: In member function 'void WebServer::processConnection(char*, int*)':
WiFlyWebServer.h:492: note: synthesized method 'WiFlyClient& WiFlyClient::operator=(const WiFlyClient&)' first required here

以下是相关的代码片段。请注意,到目前为止,我只修改了WiFlyWebServer.h(Webduino)文件:
// WiFlyWebServer.h (Webduino)
...
WiFlyServer m_server; // formerly EthernetServer and
WiFlyClient m_client; // EthernetClient
...
void WebServer::processConnection(char *buff, int *bufflen){
  ...
  // line 492
  m_client = m_server.available();
  ...
}



// WiFlyClient.h
class WiFlyClient : public Client {
 public:
  WiFlyClient();
  ...
private:
  WiFlyDevice& _WiFly;
  ...
}



// WiFlyClient.cpp
#include "WiFly.h"
#include "WiFlyClient.h"

WiFlyClient::WiFlyClient() :
  _WiFly (WiFly) {    // sets _wiFly to WiFly, which is an extern for WiFlyDevice (WiFly.h)
  ...
}


// WiFly.h
#include "WiFlyDevice.h"
...
extern WiFlyDevice WiFly;
...



// WiFlyDevice.h
class WiFlyDevice {
  public:
    WiFlyDevice(SpiUartDevice& theUart);
...



// WiFlyDevice.cpp
WiFlyDevice::WiFlyDevice(SpiUartDevice& theUart) : SPIuart (theUart) {
  /*

    Note: Supplied UART should/need not have been initialised first.

   */
  ...
}

问题源自于m_client = m_server.available();这一行,如果我注释掉它,问题就会消失(但整个程序都依赖于这行代码)。实际问题似乎是在WiFiClient对象被赋值时无法初始化(覆盖?)_WiFly成员,但我不明白为什么在没有修改的情况下可以工作而在这里却不行。
(是的,我知道头文件中有实现,我不知道为什么他们要这样写,别怪我!)
有什么见解吗?

_WiFly是为实现保留的。 - chris
@chris,不,它在全局范围内没有定义。对于这个问题,为什么不直接定义自己的赋值运算符呢?似乎_WiFly在构造函数中已经正确初始化了,所以可以忽略它。 - Lol4t0
@Lol4t0,从链接中:保留在任何范围内,包括用作实现宏的标识符:以下划线和大写字母开头的标识符。全局范围的则是以下划线开头。 - chris
3个回答

5
您的WiFlyClient中的WiFly成员是不可分配的类。这是因为赋值不能用于更改引用所指向的对象。例如:
int a = 1;
int b = 2;
int &ar = a;
int &br = b;
ar = br; // changes a's value to 2, does not change ar to reference b

由于您所有的WiFlyClient都引用同一个WiFlyDevice实例,因此可以根据编译器建议将WiFlyClient更改为使用静态成员:

// WiFlyClient.h
class WiFlyClient : public Client {
 public:
  WiFlyClient();
  ...
private:
  static WiFlyDevice& _WiFly;
  ...
};

然后,在构造函数中不进行初始化,而是在定义它的源文件中进行初始化。
WiFlyDevice & WiFlyClient::_WiFly = WiFly;

谢谢!我已经尝试将_WiFly设为静态变量,但还没有尝试在哪里定义它。现在我的代码可以编译了,时间会告诉我们它是否能正常运行... - T3db0t

0

显然问题在于WiFlyClient是不可分配的。考虑将其包含在一个std::unique_ptr(在C++03中,std::auto_ptr)中,以便您至少可以分配该类型的项目。

std::unique_ptr<WiFlyClient> m_client;

...

m_client = m_server.available();

...

// convert m_client.<...> to m_client-><...>

// change m_server.available() to return std::unique_ptr<WiFlyClient>

0

尝试重载operator=

WiFlyClient& operator= (const WiFlyClient & wi)
{
  /* make a copy here */ 
  return *this;
}

我研究了一下并尝试了几种方法,但是我无法找到制作副本的正确方法... - T3db0t

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接