0

I am programming Arduino and I have trouble when using the following code

struct myStruct {
  char variable1[10];
  char variable2[10];
  char variable3[10];

  // Constructor
  myStruct() : variable1({'\0'}), variable2({'\0'}), variable3({'\0'}) {}
};

since I get the following error:

expected primary-expression before '{' token

What is the problem? How can I solve it?

Note: The \0 is used for handling null terminated strings.


BTW: Why the following code works and the above does not?

struct myStruct {
  char variable1[10];
  char variable2[10];
  char variable3[10];
} variable = {{'\0'}, {'\0'}, {'\0'}};;
4

3 回答 3

2

Remove parens. Use braces only.

That is, instead of

variable1({'\0'})

write this,

variable1{'\0'}   //removed parens!

If you follow that, your code would look like this:

myStruct() : variable1{'\0'}, variable2{'\0'}, variable3{'\0'} {}

Any compiler that supports C++11 should be able to compile it.


In C++03, write this:

myStruct() : variable1(), variable2(), variable3() {}

That should work for this particular case. That is all you have : value-initialization. C++03 doesn't give you much freedom.

于 2013-10-01T10:58:01.263 回答
0

Assuming you just want to initialise the member variables to empty (C-style) strings, change:

  // Constructor
  myStruct() : variable1({'\0'}), variable2({'\0'}), variable3({'\0'}) {}

to:

  // Constructor
  myStruct() : variable1(""), variable2(""), variable3("") {}

Edit

Apparently some versions of gcc complain about this usage (see comments below) - this appears to be due to a bug in gcc.

于 2013-10-01T10:55:22.363 回答
0

In C++11, your code should work, although it has rather more brackets than strictly necessary.

In any C++, you could specify value-initialisation to zero-initialise the arrays:

myStruct() : variable1(), variable2(), variable3() {}

If you're being ultra-paranoid, and don't trust '\0' to be equivalent to zero, then you'd have to write to the arrays in the constructor body.

Why the following code works and the above does not?

Because it's always been possible to aggregate-initialise variables in a declaration. It's only since 2011 that it's been possible to do that in a member initialiser.

于 2013-10-01T11:01:16.580 回答