Unicode 字符问题/转换参数

Unicode characters problem/converting arguments

本文关键字:转换 参数 问题 字符 Unicode      更新时间:2023-10-16

这是不言自明的,但不能正确。这是我的代码。我需要使用该模板来处理多个文件,写入/读取它们并进行操作。

class MOBILE
{
public:
    int id;
    string tara;
    string brand;
    string culoare;
    int an;
    virtual void fscanf_el(FILE *ptr) = 0;
public:
    friend int operator < (const MOBILE&, const MOBILE&);
    friend int operator > (const MOBILE&, const MOBILE&);
    friend int operator < (const MOBILE&, const int&);
    friend int operator > (const MOBILE&, const int&);
    friend int operator == (const MOBILE&, const int&);
};

template <typename T> class GG {
public:
    vector <T> mas; 
    int size; 
    GG(char *file_name) { 
        FILE *ptr; 
        ptr = fopen(file_name, "r"); 
        T temp;
        MOBILE t[50];
        for (int i = 0; i < 50; i++)
        {
            t[i].fscanf_el(ptr);
            mas.push_back(t[i]);
        }
        fclose(ptr); 
        size = mas.size(); 
        cout << "  " << endl;
    }
};

这是我的主要.cpp

....
    int main() {
        GG <MOBILE> my_table_sort("f1.txt"); 
        GG <MOBILE> my_table_unsort("f2.txt");
        cout << "****************************************" << endl;
        menu_show(); 
    ....

我得到的错误是这 2 行

 GG <MOBILE> my_table_sort("f1.txt"); 
 GG <MOBILE> my_table_unsort("f2.txt");

错误是 C2664: 'GG::GG(GG &&(':无法将参数 1 从"常量字符 [7]"转换为"字符 *">

我不知道如何让它工作。提前谢谢。

无法将参数 1 从"常量字符 [7]"转换为"字符 *">

在C++中,字符串文本的类型为 const char[N] ,其中 N 是字符数加上一个空终止符。所以,"f1.txt""f2.txt"都是const char[7].

const char[]衰减为指向第一个字符的const char*指针。

您不能传递预期pointer-to-non-constpointer-to-const(但允许相反(。

您的GG()构造函数将非常量char*指针作为输入,因此您无法将字符串文本传递给它,除非您放弃它们的const -ness:

GG <MOBILE> my_table_sort(const_cast<char*>("f1.txt"));
GG <MOBILE> my_table_unsort(const_cast<char*>("f2.txt"));

更好的解决方案是将GG()更改为采用const char*,然后您可以传递指向它的char*const char*指针。您还应该这样做,因为无论如何fopen()都会将const char*作为输入:

GG(const char *file_name)
{
    FILE *ptr = fopen(file_name, "r");
    ...
}

或者,将GG()更改为采用std:string(),这也允许char*const char*输入:

GG(const std::string &file_name)
{
    FILE *ptr = fopen(file_name.c_str(), "r");
    ...
}