Ch13: Classes

English

提示:本页尚未翻译,当前显示英文原文。

Overview

Everything you have written so far has been made of the types somebody else defined: ::std::int_least32_t, ::fast_io::string, ::fast_io::str_btree_map. A class is how you define a type yourself.

A class puts data and the functions that work on that data into one thing, gives that thing a name, and then decides what the rest of the program is allowed to do with it. That last part is the point of the whole chapter: a class is not just a bag of fields, it is a small set of promises with the implementation hidden behind them.

The chapter follows one type from a first draft to a finished design: a point at the beginning, an account by the end. Each subchapter adds one idea, and the code grows with it.

You want to Read
Put data and behaviour into one type Ch13.1, Ch13.2
Write functions that cannot accidentally change an object Ch13.3
Decide what the outside world may touch Ch13.4, Ch13.5
Control how an object comes into existence Ch13.6
Understand the invisible this argument Ch13.7
Keep one variable or one function for the whole class Ch13.8, Ch13.9
Let exactly one outsider reach the private parts Ch13.10
A class is a promise, not a container. If a class promises “the balance is never negative”, then every function in the class has to keep that promise true, and the caller is allowed to stop checking. Encapsulation is how you make that promise believable: the data is private, so the only code that can break the promise is the code you wrote in that class.

Conventions Used in This Chapter

Contents