分配给结构数组时出错



我对c++相当陌生。我目前正在尝试在ESP32上创建一个网络广播闹钟。我已经设法打了一个电台,但我想测试一下在两个电台之间的切换。我曾尝试创建一个Station结构数组来保存每个Station的相关信息,但在尝试分配给数组中的不同元素时,我总是会遇到同样的错误。这可能是一个非常简单的错误,但我无法弄清楚,在其他地方也看不到太相似的东西。

#include <Arduino.h>
#include "WiFi.h"
#include <Audio.h> 
#include <string.h>
#include <SPI.h> 
#define I2S_DOUT     25
#define I2S_BCLK      27
#define I2S_LRC        26  
Audio audio;
#define SSID ""
#define PASSWORD "" 

//function to change station    
void changeStat() {
int statIndex = (statIndex+1)%2; 
};

void connectToWiFi(){
Serial.print("Connecting to Wifi"); 
WiFi.mode(WIFI_STA);
WiFi.begin(SSID, PASSWORD);
while(WiFi.status() != WL_CONNECTED){
Serial.print('.'); 
delay(1000); 
}
Serial.print("n Connected n");
Serial.println(WiFi.localIP());
}
void setup() {
Serial.begin(9600);   
//Initialising array of station structures
struct Station{
char name[15];  
char URL[130]; 
};  
Station Stats[2]; 
int statIndex = 0;
Stats[0] = {"BBC 6Music", "http://stream.live.vc.bbcmedia.co.uk/bbc_6music"};
Stats[1] = {"BBC Rad4", "http://stream.live.vc.bbcmedia.co.uk/bbc_radio_fourlw"};
connectToWiFi(); 
audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT); 
audio.setVolume(5); 
audio.connecttohost(Stats[statIndex].URL);
}
void loop() {  
audio.loop();
}

具体来说,我在线路Stats[0] and Stats[1]上得到的错误是no match for 'operator=' (operand types are 'setup()::Station' and '<brace-enclosed initializer list>')但我见过很多其他人使用这种任务

此语法使用初始值设定项列表,这是C++2011版本中添加的一个功能。

struct Station
{
char name[15];  
char URL[130]; 
};  
Station station = { "BBC 6Music", "http://stream.live.vc.bbcmedia.co.uk/bbc_6music" };

如果可以的话,一定要切换到最新的编译器,至少要处理C++14。

如果没有,您仍然可以使用C样式:

Station station;
strcpy(station.name, "BBC 6Music");
//...

另一种解决方案是为Station:提供一个用户定义的构造函数

struct Station
{
char name[15];  
char URL[130]; 
Station(char const* _name, char const* _url) { /* ... */ }
};
Station station("BBC 6Music", "http://stream.live.vc.bbcmedia.co.uk/bbc_6music");

最新更新