阅读 Andrew Koenig 和 Barbara E. Moo 的“Accelerated C++”的另一个问题,我在关于构造函数(5.1)的章节,使用前面的例子。
他们写
我们要定义两个构造函数:第一个构造函数不带参数并创建一个空
Student_info
对象;第二个引用输入流并通过从该流中读取学生记录来初始化对象。
导致使用Student_info::Student_info(istream& is) {read(is);}
作为第二个构造函数的例子
将实际工作委托给 read 函数。[...] read 立即赋予这些变量新的值。
Student_info
班级是
class Student_info {
public:
std::string name() const (return n;}
bool valid() const {return !homework.empty();}
std::istream& read(std::istream&);
double grade() const;
private:
std::string n;
double midterm, final;
std::vector<double> homework;
};
既然read
已经定义为Student_info
类下的函数,为什么还要使用第二个构造函数——这不是双重工作吗?为什么不只使用默认构造函数,然后使用函数,因为两者都已经定义了?