错误 C2059:语法错误:从结构成员声明'constant'
error C2059: syntax error: 'constant' from struct member declarations
这看起来像是一个简单的类和结构定义,但在将类实例声明为结构成员时,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 *
?
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- 为什么static_assert错误:即使我传递常量"expression must have a constant value"?
- 为什么在main()之前断言会导致语法错误"error: expected ')' before numeric constant"?
- 错误 C2059:语法错误:从结构成员声明'constant'
- 如何修复此错误"the value of 'x1' is not usable in a constant expression"?static_assert
- 外部"C"导致错误"expected '(' before string constant"
- boost::asio::d eadline_timer 导致"a function call cannot appear in a constant-expression"错误
- 错误 C2059:语法错误: 'constant'
- 错误 C2059:语法错误'constant'
- 需要解决方案:错误C2059:语法错误'constant'
- 视觉C++错误 C2143:语法错误:'constant'之前缺少';'
- 无符号字符给出错误:"expression must have a constant value"
- 编译器错误"character constant too long for its type" 。怎么了?
- 获取错误"array bound is not an integer constant before ']' token"
- 'Constant Expression Required' 错误,同时将正式参数保留为常量
- 如何编译 MSHTML v9 的.dll。我目前收到 100 多个"MIDL 2035: constant expression expected"错误
- 另一个"expected unqualified-id before numeric constant"错误
- 模板类构造函数,在第二个模板中有一个参数引发错误"constant"