c++ - 带参数的构造函数初始化

标签 c++ class constructor

另一个问题来自阅读 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/

相关文章:

c++ - 标志控制 while 循环搜索 txt 文件

c++ - 我的新 Unique_ptr 的所有权?

c++ - QDrag 和 Skype 问题(仅限 win)

swift - 快速计算一个类的实例数

python - 如何从动态导入的类中调用方法

java - 更改静态变量适用于 Primitive Wrapper 但不适用于 Primitive 类型

C++:通过引用另一个类成员变量来初始化类成员变量?

java - 在调用 super 之前在构造函数中转换变量?

c++ - 如何在 Eclipse 中配置 Crypto++?

java - 在赋值上复制构造函数