我想使用此函数将char转换为字符串:

int charIndexDistance (char a, char b)
{
    if (indexical) {
        string test_a = convertOntology((string)a, 0);
        string test_b = convertOntology((string)b, 0);
        cout << test_a << " " << test_b << endl;

        int test = abs(char_index[a] - char_index[b]);
        return test; //measure indexical distance between chars
    } else
        return 1;
}

但是我得到这个“错误C2440:'type cast':无法从'char'转换为'std::string”

什么是问题?以及如何将字符转换为字符串-我应该使用字符串附加吗?

同样,coutint test用于调试目的,以后将被删除

最佳答案

根本就没有这种转换。相反,您必须手动构造一个字符串:

string(1, a)

这使用了constructor taking a length and a char to fill the string with

在您的代码上下文中:
string test_a = convertOntology(string(1, a), 0);
string test_b = convertOntology(string(1, b), 0);

即使存在适当的构造函数/ Actor 表,由于you should avoid C-style casts in C++,您的代码也会很糟糕。这种情况将要求使用static_cast

关于c++ - (字符串)字符类型转换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15229779/

10-11 03:08
查看更多