简体   繁体   English

VS2008 C ++编译器错误?

[英]VS2008 C++ Compiler error?

this compiles :-) 这个编译:-)

string name;
name = 1;

this does not: 这不是:

string name = 1;

any thoughts? 有什么想法吗?

I know that this is wrong. 我知道这是错的。 . . that is not the point. 这不是重点。 The first gives a smiley face. 第一个给人一个笑脸。

The first compiles because the assignment operator is called what has one signature of "string& operator= ( char c )" and the compiler can convert 1 into a char. 第一个编译是因为赋值赋值运算符被称为“string&operator =(char c)”的一个签名,编译器可以将1转换为char。

The second won't compile because it calls the copy constructor which has no compatible signature. 第二个不会编译,因为它调用没有兼容签名的复制构造函数。

The second example is really initialization rather than assignment, ie it calls a constructor rather than operator= . 第二个例子是初始化而不是赋值,即它调用构造函数而不是operator= Evidently class string does not have a constructor that takes an integer as an argument, but it's assignment operator is ok with it. 显然,类string没有一个以整数作为参数的构造函数,但是它的赋值运算符是可以的。 And the reason you get a smiley face is that it is the character with the ASCII value of 1. 你得到笑脸的原因是它是ASCII值为1的字符。

By the way, this is not specific to Visual Studio. 顺便说一句,这不是Visual Studio特有的。 Any C++ compiler should behave the same way. 任何C ++编译器都应该以相同的方式运行。

Not to do with the question, but why don't you (and many others) post compilable code. 与问题无关,但为什么不(和许多其他人)发布可编辑的代码。 Would : 将 :

#include <string>
using namespace std;

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

have been too much to ask for? 有太多要求了吗? Given that, we can see that "string" actually refers to std::string and not some random class. 鉴于此,我们可以看到“string”实际上是指std :: string而不是一些随机类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM