今天做了一個很簡單的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;
}
};