错误 C2059:语法错误:从结构成员声明'constant'

error C2059: syntax error: 'constant' from struct member declarations

本文关键字:错误 constant 声明 结构 C2059 语法 成员      更新时间:2023-10-16

这看起来像是一个简单的类和结构定义,但在将类实例声明为结构成员时,Visual Studio C++会发出编译器错误,但可以毫无问题地声明同一类的全局实例。编译错误发生在"Thing"结构成员(Thing thing1(1,"1"(上

如果类成员被声明为const并使构造函数的参数为const ,则会出现相同的编译错误

class Thing
{
public:
Thing(int addr, char* str) : theaddr(addr), name(str)      {}
void info()             { printf("%d %sn", theaddr, name); }
int  read()             { /* code to read */                }
void write(int newval)  { /* code to write newval */        }
private:    
int  theaddr;
char *name;
};
Thing global_thing(0,"0");  // WORKS no problem
struct Things
{
Thing thing1(1,"1");    // ERROR on "Thing" members in struct
Thing thing2(2,"2");
.
.
.
Thing thingN(3,"3");
}specificThings;

结构定义中的'Thing'成员出现编译器错误"错误C2059:语法错误:'constant'"。

上面的Thing类示例是为了演示这个问题而设计的。我实际想做的是声明一个类来访问一个具有寄存器地址的SPI设备。该系统有几个设备,其中一些设备有通用的寄存器名(如"config"(。其想法是让结构具有作为类实例的成员来设置固定的寄存器地址。此外,我希望能够使用"info(("类型函数来打印相关的寄存器名称,以进行调试。

当时的想法是这样做:

class DeviceReg
{
// content like the "Thing" class
};
struct
{
DeviceReg    config(0x22,"config");
DeviceReg    status(0x33,"status");
// and so on...
}rfdev;

然后设备访问可能类似于:

rfdev.config.write(0x17);
rfdev.config.info();

可能还有其他一些设备可以访问,比如:

tempsensor.config.write(0x55);
tempsensor.info();

因此,多个设备可以具有配置或状态寄存器,而无需强制根据设备命名每个配置寄存器。

既然我想做的事情显然违反了C++语法,那么有没有其他方法可以达到预期的结果呢?

类成员的默认类初始化器需要基于{}的初始化器语法或基于=的初始化器句法。对于这样的初始化程序,没有基于()的语法。

语法正确的变体可能看起来像

struct Things
{
Thing thing1{ 1, "1" };
Thing thing2{ 2, "2" };
// ...
Thing thingN{ 3, "3" };
} specificThings;

但是,这将导致下一个错误:不允许使用字符串文字来初始化char *指针。可能使用const char *