3
#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

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

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

4

3 回答 3

22

尝试更换

 char c = "i";

 char c = 'i';
于 2012-08-19T12:45:57.850 回答
12

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

你几乎肯定想要'i'

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

However, if that were the case, I'd give serious thought to using the C++ std::string type 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.

于 2012-08-19T12:46:08.557 回答
10

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

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

char 文字只是chars

于 2012-08-19T12:45:42.997 回答