VS2008 C ++ compiler error?

this compiles :-)

string name;
name = 1;

      

this is not true:

string name = 1;

      

any thoughts?

I know this is wrong ... it is not the point. The first gives an emoticon.

+2


source to share


3 answers


The first one is compiled because the assignment operator is said to have one signature "string & operator = (char c)" and the compiler can convert 1 to char.



The second one won't compile because it calls a copy constructor that doesn't have a compatible signature.

+14




The second example is really initialization, not assignment, i. That is, it calls the constructor, not operator=

. Obviously the class string

doesn't have a constructor that takes an integer as an argument, but the assignment operator is fine. And the reason you get an emoji is because it is a character with an ASCII value of 1.



By the way, this is not the case for Visual Studio. Any C ++ compiler should behave the same.

+4


source


Not relevant to the question, but why don't you (and many others) post the compiled code. Will be:

#include <string>
using namespace std;

int main() {
    string name;
    name = 1;
    string name2 = 1;
}

      

was it too much to ask for? With this in mind, we can see that "string" actually refers to std :: string, and not some random class.

+1


source







All Articles