首页 > 解决方案 > 调用函数时从 'char' 到 'char*' 的无效转换(c++)

问题描述

每次我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 位置上的文件中的字符。是什么导致了这个问题?

标签: c++pointerschartype-conversion

解决方案


问题:

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();
        ...
    }

此外,如果没有可用的 char,则 if 仍可能被执行并返回 ture,因为无法保证该函数将返回 0

更喜欢 :

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

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


推荐阅读