Errors C2664 and E0167, stumped

谁说我不能喝 提交于 2019-12-04 04:16:45

问题


I'm taking a c++ beginner's distance class and can't solve this compile error. It's written exactly as in the example book, and when my brother cuts and pastes it into his VS2015 it works fine, but in my VS2017 it doesn't. I have uninstalled and re-installed VS2017 community to no avail.

I have only been coding for 2 weeks so I'm very, very new to this.

The error codes I get are:

Error E0167 argument of type "const char " is incompatible with parameter of type "char
Error C2664 'void Hello(char )': cannot convert argument 1 from 'const char [8]' to 'char '

The code:

// FUNCTION: Hello, prints out a welcome message on the screen.
void Hello(char* name)
{
 cout << "Hello " << name << "!";
}

// FUNCTION: Main, program start.
int main()
{
 Hello("Krister");
 cin.get();
 return 0;
}

I really hope someone can help me with this.

All the best, Jepp


回答1:


A string literal may be referred to by a const char*.

It may not be referred to by a char*; this was possible in old versions of C, and some older C++ compilers permitted it with a warning. In modern times it is completely prohibited.

By passing "Krister" to a function taking char*, you are asking the compiler to try to convert one to the other; it is failing, due to the above rule, as evidenced by the error message.

Chuck a const in there for great success.

If that code came from a textbook, lose it. Here is a list of good C++ books.




回答2:


Just to complement the answer by Lightness Races in Orbit, which describes what you definitely should do. The reason for the difference between VS2015 and VS2017 is that the later sets the /permissive flag off by default, unlike the former.

It means that VS2017 may very well reject code that "your brother's" VS2015 accepts, unless the project options are tinkered with.

I recommend you keep the flag in its off state. Strict conformance is good, it makes you pick up better habits and write more portable C++.



来源:https://stackoverflow.com/questions/48987994/errors-c2664-and-e0167-stumped

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!