Hi, all~
please look at this:
one of my book said it would cause an error when compiling, but my compiler do accept it and pring a "!" as string in screen. is it relative wth compilers ?Code:string s='!';
Hi, all~
please look at this:
one of my book said it would cause an error when compiling, but my compiler do accept it and pring a "!" as string in screen. is it relative wth compilers ?Code:string s='!';
Never end on learning~
>>string s="!";
When all else fails, read the instructions.
If you're posting code, use code tags: [code] /* insert code here */ [/code]
It seems you've answered your own question. The book says it'll throw an error but when you tested it, it didn't - therefore its probably a compiler specific issue. I would stick to the double quotes though, as demonstrated rather nicely by Hammer
Couldn't think of anything interesting, cool or funny - sorry.
I think the book is wrong.
Look -- the string class has a char assignment operator:
basic_string& operator=(charT);
Therefore, string s = '!'; is perfectly valid.
Check out this, the constructors for the string class. There isn't one where it takes a single char as an arg.Originally posted by Davros
I think the book is wrong.
Look -- the string class has a char assignment operator:
basic_string& operator=(charT);
Therefore, string s = '!'; is perfectly valid.
When all else fails, read the instructions.
If you're posting code, use code tags: [code] /* insert code here */ [/code]
To follow on from Hammer....
Remember that string foobar = "Hello World" uses the copy constructor....not the assignment operator...If you want, you can
Code:string foobar; foobar = 'h';
OK, I take your point. There doesn't seem to be a char constructor.
So we are saying that:
string s = '!';
is invalid, but
string s;
s = '!';
is valid.
It seems a little strang that we have an assignment operator, but not a char copy constructor. Is there any reason for this? May the copy constructor is implemented but not documented.
An error on my part.....I dont think it was a copy contructor...
More likely the basic_string(const T*) constructor.......
I was always with Dev-C++ so I want to know it this format is valid in VC or BCB ?
Never end on learning~
Hi,
I was wondering why
string s = '!';
isn't valid while
string s;
s='!';
is valid?
string s;
s = '!';
is valid because string (basic_string) has an assignment operator which accepts a single char. Which looks like this:
basic_string& operator=(charT);
However, the string class does not have a constructor which accepts a single char. When we write :
string s = '!';
it would be the constructor which is called in this case, not the assignment operator.
While it seems an oversight not to include a constructor, it's not really a big issue, because we can still write:
string s = "!";
In this case, "!" is char string array, i.e. a pointer to a char string (char*), rather than just a single char itself. Notice the double quote, instead of single.