【问题标题】:Invalid conversion from 'char' to 'char*' while calling a function (c++)调用函数时从“char”到“char*”的无效转换(c++)
【发布时间】:2019-05-10 02:09:50
【问题描述】:

每次我用这段代码写loadChar(charVariable,positonOfCharacter)

bool LoadEntity::loadChar(char * outputChar,int position)
    {
        ifstream file(nameOfFile.c_str());

        if(!(file.good()))
            return false;

        file.seekg(position);
        if(file.get())
        {
            * outputChar = file.get();
            return true;
        }
        else
            return false;
    }`

我收到此错误:invalid conversion from 'char' to 'char* 如果函数正确运行,代码应该返回 bool 并将 char outputChar 的值更改为 int 位置的文件中的字符。是什么导致了这个问题?

【问题讨论】:

  • 你需要传递一个指针,而不是一个字符的值。错误是不言自明的。
  • get a couple of good books,了解references
  • 请注意,您调用了两次file.get(),因此您读取了两个不同的值。
  • 更改为 bool LoadEntity::loadChar(char& outputChar,int position) 并将 outputChar 视为普通变量(即无需取消引用)。
  • loadChar(&charVariable, positonOfCharacter)

标签: c++ pointers char type-conversion


【解决方案1】:

问题:

char charVariable;
...
loadChar(charVariable, positonOfCharacter); 

在这里,您尝试传递 char 值,而不是函数预期的指针(即 char*)。这是非法的。

简单的解决方案:

调用函数时使用变量的地址:

loadChar(&charVariable, positonOfCharacter);    // note the &

替代方案:

如果您对指针不太熟悉,您还可以更改函数的签名并使用引用而不是指针。引用允许您更改原始变量的值:

bool LoadEntity::loadChar(char& outputChar, int position)  // note the &
{
    ... 
        outputChar = file.get();      // note: no * anymore
    ...
}

不相关的问题:

您对get() 的使用存在问题。以下将导致您读取两次文件但忽略第一个输入:

    if(file.get())
    {
        * outputChar = file.get();
        ...
    }

此外,如果没有可用的字符,则 if 仍可能被执行并返回 ture,因为无法保证 that the function will return 0

喜欢:

    if(file.get(*outputChar))
    {
        return true;
    }

别担心:如果无法从文件中读取任何字符,则不会更改输出字符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    相关资源
    最近更新 更多