【问题标题】:no convert function c++没有转换函数 c++
【发布时间】:2020-10-06 10:44:47
【问题描述】:

我经常遇到这个问题 我已将 cours 类定义为学生类中的对象,现在我无法将其保存在数组中

Screenshot of error as presented by IDE

   list<student> listStudents;
   FILE* f;

   f= fopen("s.t.h.txt", "r");
    
    for (int i=0;i<cont;i++)
    {
        string arr[4];
        fscanf(f, "%d %s %s ", &arr);


        student  st1;
        st1.stu_id = stoi(arr[0]);
        st1.stu_name = arr[1];
        st1.co_num = stoi(arr[2]);
        st1.co = arr[3];
        listStudents.push_back(st1);
    }; 

     class student {
     public:
    int stu_id;
    string stu_name;
    int co_num;
    course* co;
    int s;
    student(int s);
    int max = 5;}

【问题讨论】:

  • 为什么不能保存在数组中?请解释您的问题
  • 你得到什么错误?
  • std::string 作为参数传递给fscanf?嗯,这是一个想法。
  • 另一件事你的问题不是你不能将学生存储在列表中。问题之一是这一行 st1.co = arr[3]; 你不能只说 std::string 现在是 course 你必须以某种方式转换它

标签: c++ list


【解决方案1】:

您不能仅仅通过愿意将其从您创建的数据类型转换为字符串。您可以做的是将数组初始化为父数据类型,然后将任何继承树添加到数组中,因为它是“是”关系。

另一个选择是创建一个“getter”。这意味着在课程对象中添加一个函数,例如 getName(),它返回一个字符串。

底线是数组是字符串类型,课程对象不是字符串,但课程名称可能是!

【讨论】:

    【解决方案2】:

    在您的链接图像中,错误位于st1.co = arr[3]; 行。

    co是一个类型为course *的字段,arr是一个string的数组。因此编译器会抱怨,因为您试图用string 设置course *

    更多:

    你认为fscanf(f, "%d %s %s ", &amp;arr); 会做什么?如果您使用 C++,则使用 C++ 构造,也就是 cin...

    【讨论】:

    • 感谢文件
    猜你喜欢
    • 2018-07-22
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 2017-09-25
    • 2011-12-24
    相关资源
    最近更新 更多