I'm looking for an easy way to build an array of strings at compile time. For a test, I put together a class named Strings
that has the following members:
Strings();
Strings(const Strings& that);
Strings(const char* s1);
Strings& operator=(const char* s1);
Strings& operator,(const char* s2);
Using this, I can successfully compile code like this:
Strings s;
s="Hello","World!";
The s="Hello"
part invokes the operator=
which returns a Strings&
and then the operator,
get called for "World!"
.
What I can't get to work (in MSVC, haven't tried any other compilers yet) is
Strings s="Hello","World!";
I'd assume here that Strings s="Hello"
would call the copy constructor and then everything would behave the same as the first example. But I get the error: error C2059: syntax error : 'string'
However, this works fine:
Strings s="Hello";
So I know that the copy constructor does at least work for one string. Any ideas? I'd really like to have the second method work just to make the code a little cleaner.
I think that the comma in your second example is not the comma operator but rather the grammar element for multiple variable declarations.
e.g., the same way that you can write:
int a=3, b=4
It seems to me that you are essentially writing:
Strings s="Hello", stringliteral
So the compiler expects the item after the comma to be the name of a variable, and instead it sees a string literal and announces an error. In other words, the constructor is applied to "Hello", but the comma afterwards is not the comma operator of Strings.
By the way, the constructor is not really a copy constructor. It creates a Strings object from a literal string parameter... The term copy constructor is typically applied to the same type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With