单参数的构造函数可以发生从参数类型到类类型的隐式转换,例如:
Student doh("Homer",10);
doh = 5;
则程序会将int 5转换为Student(5),赋值给doh;
加上explicit会关闭这种转换;
#include <iostream>
#include <valarray>
#include <string>
using namespace std;
typedef valarray<double> ArrayDb;
typedef valarray<double> ArrayDb;
class Student
{
public:
Student():name("Null Student"),scores(){}
explicit Student(const string &s):name(s),scores(){}
explicit Student(int n):name("Nully"),scores(n){}
Student(const string &s,int n):name(s),scores(n){}
Student(const string &s,const ArrayDb &a):name(s),scores(a){}
Student(const char *str,const double *pd,int n):name(str),scores(pd,n){}
~Student(){}
double Average() const;
const string &Name() const;
double& operator[](int i);
double operator [] (int i) const ;
//friends
friend istream& operator>>(istream& is,Student &stu);
friend istream& getline(istream& is,Student &stu);
friend ostream& operator<<(ostream& os,const Student &stu);
private:
typedef valarray<double> ArrayDb;
string name;
ArrayDb scores;
ostream& arr_out(ostream &os) const;
};
double Student::Average () const
{
if(scores.size () >0)
return scores.sum ()/scores.size ();
else
return 0;
}
const string & Student::Name() const
{
return name;
}
double &Student::operator [](int i)
{
return scores[i];
}
double Student::operator [] (int i) const
{
return scores[i];
}
ostream& Student::arr_out(ostream &os) const
{
int lim = scores .size ();
if(lim > 0)
{
for(int i = 0;i<lim;i++)
{
os<<scores[i]<<" ";
if(i % 5 == 4)
os<<endl;
if(i % 5 != 0)
os<<endl;
}
}
else
os<<"empty array";
return os;
}
istream & operator >>(istream &is,Student &stu)
{
is>>stu.name;
return is;
}
istream & getline(istream& is,Student &stu)
{
getline (is,stu.name);
return is;
}
ostream & operator <<(ostream &os,const Student &stu)
{
os<<"Scores for "<<stu.name<<":\n";
stu.arr_out (os);
return os;
}
void set(Student &sa,int n)
{
cout<<"Please enter the student's name:"<<endl;
getline (cin,sa);
cout<<"Please enter"<<n<<"quiz scores"<<endl;
for (int i = 0; i < n; ++i) {
cin>>sa[i];
}
while (cin.get () != '\n') {
continue;
}
}
const int pupilsl = 3;
const int quizze = 5;
int main()
{
Student ada[pupilsl] = {
Student(quizze),
Student(quizze),
Student(quizze)
};
for (int i = 0; i < pupilsl; ++i) {
set (ada[i],quizze);
}
cout <<"\nStudent List:\n";
for (int i = 0; i < pupilsl; ++i) {
cout<<ada[i].Name ()<<endl;
}
cout<<"\nResults:";
for (int i = 0; i < pupilsl; ++i) {
cout<<endl<<ada[i];
cout<<"average:"<<ada[i].Average ()<<endl;
}
cout<<"Done.\n";
return 0;
}