另一个问题来自阅读 Andrew Koenig 和 Barbara E. Moo 的“加速 C++”,我在关于构造函数 (5.1) 的章节中使用示例 before .
他们写
we'll want to define two constructors: the first constructor takes no arguments and creates an empty
Student_info
object; the second takes a reference to an input stream and initializes the object by reading a student record from that stream.
导致使用 Student_info::Student_info(istream& is) {read(is);}
作为第二个构造函数的例子
delegates the real work to the read function. [...] read immediately gives these variables new values.
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
类下的函数,为什么需要使用第二个构造函数 - 不是吗这不是双重工作吗?为什么不直接使用默认构造函数,然后使用函数,因为两者都已定义?
最佳答案
这不是双重工作,相反,它简化了实例化类的调用者的对象初始化
如果你每次都用一个构造函数创建类
std::istream is = std::cin;
Student_info si();
si.read(is);
// si.foo();
// si.bar();
// si.baz();
也许可以添加一些可以在构造函数中完成的其他操作。这样当你需要实例化类时就不用再写它们了。如果创建 10 个实例,则必须编写
( 10 -1 = ) 9 行,这不是 OOP 的好方法
Student_info::Student_info(istream& is)
{
read(is);
//foo();
//bar();
//baz();
}
但是当你像上面那样定义两个构造函数时,你可以像这样使用类
std::istream is = std::cin;
Student_info si(is);
OOP 的主要目标之一是编写可重用而非 self 重复的代码,另一个目标是 seperation of concerns .在许多情况下,实例化对象的人不需要知道类的实现细节。
在您的示例中,read
函数在构造函数内部调用时可以是私有(private)的。这给我们带来了 OOP 的另一个概念 Encapsulation
最后,这不是双重工作,它是软件设计的好方法
关于c++ - 带参数的构造函数初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15564816/