c ++ oop错误。没有匹配的功能

时间:2016-03-28 21:12:08

标签: c++ oop

我编译时不断收到这些错误

  

60 35 H:\ OCC \学生模拟器程序2.cpp [错误]无匹配   调用'student :: student(int,double,int,const char)的函数   [6])'

     

60 35 H:\ OCC \学生模拟器程序2.cpp [错误]候选人是:

     

22 2 H:\ OCC \学生模拟器程序2.cpp student :: student()22 2   H:\ OCC \学生模拟器程序2.cpp候选人期望0   参数,4提供

     

13 7 H:\ OCC \学生模拟器程序2.cpp student :: student(const   学生&)13 7 H:\ OCC \学生模拟器程序2.cpp候选人   期望1个参数,4提供

代码:

//student simulator

#include <string>
#include <iostream>
#include <cstdlib>

using namespace std;

class student {
private:
int     num;    //student num
float   grade;  //student grade
int     workEthic; //rating of student work ethic (1-10)
string personalityType; //string value 

public:

student() :num(0),grade(0),workEthic(0),personalityType("dead")
{}
void  askQuestion ()
{
    workEthic++;
    grade+=0.5;
}
void  sleep()
{
    workEthic=0;
    personalityType= "sleepy";
    grade-=3.3;

}
void  wake ()
{
    workEthic+=3;
    personalityType="awake";
    grade+=3.2;
}
void display()
{
    cout<<"id num="<<num<<endl;
    cout<<"grade="<<grade<<endl;
    cout<<"work ethic="<<workEthic<<endl;
    cout<<personalityType<<endl;
}
};


int main()
{
student matthew (5,96.5,2,"bored");
matthew.sleep();
matthew.display();
system("PAUSE");    

matthew.wake();
matthew.askQuestion();
matthew.display();
return 0;
}

我对c ++很新,我似乎无法弄清楚为什么会出错。

3 个答案:

答案 0 :(得分:1)

请阅读错误消息:

  

错误:没有用于初始化&#39; student&#39;

的匹配构造函数

您没有定义一个采用intfloatint,字符串文字的构造函数。

答案 1 :(得分:1)

main()中,您调用class student的构造函数,该构造函数接收四个参数:

student matthew(5, 96.5, 2, "bored");

但是你的类只定义了没有接收任何参数的默认构造函数,并使用parantheses中的值初始化类成员:

student() :num(0), grade(0), workEthic(0), personalityType("dead")
    {}

您可以在main()中调用该默认构造函数,不带参数,也可以不使用parantheses:

student matthew;

要像main() student matthew(5, 96.5, 2, "bored");一样提供初始值,你必须向class student添加一个重载的构造函数,它接受四个参数并使用提供的值初始化类成员像:

student(int n, float g, int wE, string pT)
        : num(n),
          grade(g),
          workEthic(wE),
          personalityType(pT)
{}

Live

答案 2 :(得分:0)

该类未声明具有四个参数的构造函数。所以这句话

student matthew (5,96.5,2,"bored");

无效。

您需要在类中定义这样的构造函数,以使上述语句正确。

目前,该类具有不接受参数的默认构造函数。