今天做了一个很简单的c++实验。但因为第一次用c++编写面向对象的程序,还是踩了个坑。
报错代码:
#include<iostream>
#include<string>
#include<ctime>
#include<cstdlib>
using namespace std;
class Student{
public:
string Id;
double Score;
public:
Student(string id,double score){
Id=id;
Score=score;
}
};
class Select{
private:
int N;
int count=0;
Student stuList[100];
public:
Select(int n){
N=n;
}
void read(){
for(int i=0;i<N;i++){
cout<<"请输入第"<<i+1<<"位学生的学号和分数"<<endl;
string id;
double score;
cin>>id>>score;
Student stu(id,score);
if(stu.Score>80)
stuList[count++]=stu;
}
}
void printOne(){
srand(time(0));
int r=rand() % count;
cout<<"抽签出的学生学号和分数分别为:"<<endl;
cout<<stuList[r].Id<<' '<<stuList[r].Score << endl;
}
};
int main(){
int N;
cout<<"请输入学生总数"<<endl;
cin>>N;
Select select(N);
select.read();
select.printOne();
return 0;
}在这里插入代码片
报错内容:
24 16 [Error] no matching function for call to 'Student::Student()'
原因:
Student类中定义了新的需要参数构造函数,覆盖了默认的构造函数。在Select类中定义Student的数组时,无法调用构造函数,导致没法实例化。
解决方法:添加默认的构造函数到Student类中,修改Student类:
class Student{
public:
string Id;
double Score;
public:
Student(){}
Student(string id,double score){
Id=id;
Score=score;
}
};