C++ 错误:从“const char*”到“char”的无效转换[-fpermissive]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12026567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:47:25  来源:igfitidea点击:

error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive]

c++

提问by VarunVyas

#include<stdio.h>
#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;

class base {
 public:
    int lookup(char c);
}; // class base

int base::lookup(char c)
{
    cout << c << endl;
} // base::lookup

int main() {
    base b;
    char c = "i";
    b.lookup(c);
} // main

On Compiling above code I am getting below error :

在编译上面的代码时,我收到以下错误:

g++ -c test.cpp test.cpp: In function ‘int main()': test.cpp:20:10: error: invalid conversion from ‘const char*' to ‘char' [-fpermissive]

g++ -c test.cpp test.cpp:在函数“int main()”中:test.cpp:20:10:错误:从“const char*”到“char”的无效转换[-fpermissive]

回答by mathematician1975

Try replacing

尝试更换

 char c = "i";

with

 char c = 'i';

回答by paxdiablo

"i"is not a character, it's a character array that basically decays to a pointer to the first element.

"i"不是字符,它是一个字符数组,基本上衰减到指向第一个元素的指针。

You almost certainly want 'i'.

你几乎肯定想要'i'

Alternatively, you may actually wanta lookup based on more than a single character, in which case you shouldbe using "i"but the type in that case is const char *rather than just char, both when defining cand in the base::lookup()method.

或者,您实际上可能需要基于多个字符的查找,在这种情况下,您应该使用,"i"但在这种情况下,在定义和方法中的类型都const char *不仅仅是。charcbase::lookup()

However, if that were the case, I'd give serious thought to using the C++ std::stringtype rather than const char *. It may not be necessary,but using C++ strings may make your life a lot easier, depending on how much you want to manipulate the actual values.

但是,如果是这种情况,我会认真考虑使用 C++std::string类型而不是const char *. 这可能不是必需的,但使用 C++ 字符串可能会让您的生活更轻松,这取决于您想要操纵实际值的程度。

回答by Mankarse

"i"is a string literal, you probably wanted a char literal: 'i'.

"i"是一个字符串文字,你可能想要一个字符文字:'i'

String literals are null terminated arrays of const char(which are implicitly converted to char const*when used in that expression, hence the error).

字符串文字是以空终止的数组const charchar const*在该表达式中使用时隐式转换为,因此出现错误)。

char literals are just chars

字符文字只是chars