【问题标题】:No matching function for call to vector没有匹配函数调用向量
【发布时间】:2018-03-04 20:58:43
【问题描述】:

我收到错误:[Error] no matching function for call to 'subjects::subjects(std::string&, std::string&, std::string&, int&, int&)'。 这是我的代码:

void listInput(subjects a){
//  subjects a;
    cout<<"Enter the name of the subject"<<endl;
    cin>>a.subjectName;
    while(a.subjectName.empty()){
        cout<<"Error, subject name must not be empty"<<endl;
        cin>>a.subjectName;
    }
    cout<<"Enter the name of lecturer"<<endl;
    cin.ignore();
    getline(cin, a.lectName);
    while(checkName(a.lectName)!=1){
        cout<<"Error, invalid input"<<endl;
        getline(cin, a.lectName);
    }
    cout<<"Enter the surname of lecturer"<<endl;
    getline(cin, a.lectSurname);
    while(checkName(a.lectSurname)!=1){
        cout<<"Error, invalid input"<<endl;
        getline(cin, a.lectSurname);
    }
    a.credits=a.enterNumber("Enter the number of credits\n");
    a.studentnum=a.enterNumber("Enter the number of students\n");
    a.entry.push_back(new subjects(a.subjectName, a.lectName,a.lectSurname,a.credits, a.studentnum));
}

还有头文件:

#ifndef SUBJECT
#define SUBJECT

#include <string>
#include <vector>


class subjects{
    private:
        std::string subjectName;
        std::string lectName;
        std::string lectSurname;
        int credits;
        int studentnum;

    public:
        subjects(){
            subjectName="";
            lectName="";
            lectSurname="";
            credits=0;
            studentnum=0;
        }
        int userChoice();
        int enterNumber(std::string name);
        void menu();
        friend void listInput(subjects a);
        bool checkName(std::string &text);
        std::vector<subjects*> entry;

};

#endif

我该如何解决这个问题?或者在这种情况下我不应该使用向量,忽略友元函数,因为我们需要使用它

【问题讨论】:

  • 好吧,你没有一个带参数的构造函数——那么你希望new subjects(a.subjectName, a.lectName,a.lectSurname,a.credits, a.studentnum)如何工作?
  • subjects::subjects 不接受参数,根据标题
  • 您的问题标题与内容无关。
  • 首先,将您的代码简化为 MCVE。这不仅是让您对主题提出问题所必需的,还可以帮助您理解问题。

标签: c++


【解决方案1】:

您没有接受所有这些参数的构造函数。将另一个构造函数添加到 subjects,它采用适当的参数,您的代码应该没问题。

【讨论】:

    【解决方案2】:

    您有一个默认构造函数,但没有构造函数采用四个参数。您可以通过添加具有默认值的构造函数同时拥有两者:

    subjects(
        const std::string subjectName=""
    ,   const std::string lectName = ""
    ,   const std::string lectSurname=""
    ,   const int credits = 0
    ,   const int studentnum = 0
    ) : subjectName(subjectName)
    ,   lectName(lectName)
    ,   lectSurname(lectSurname)
    ,   credits(credits)
    ,   studentnum(studentnum)
    {
    }
    

    此方法允许您使用零、一、二、三、四或五个参数调用subjects 构造函数。当传递的参数个数少于五个时,其余的使用默认值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-09
      • 1970-01-01
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      相关资源
      最近更新 更多