官术网_书友最值得收藏!

Behavior

In previous examples, we assigned 5 and then 4 to the rating member variable. We can easily make things unexpectedly wrong by assigning invalid values to the object, like so:

cpp_book.rating = -12;

-12 is invalid in terms of the rating of a product and will confuse users, if allowed to. We can control the behavior of the changes made to the object by providing setter functions:

void set_rating(Product* p, int r) {
if (r >= 1 && r <= 5) {
p->rating = r;
}
// otherwise ignore
}
...
set_rating(&cpp_book, -12); // won't change the state

An object acts and reacts to the requests from other objects. The requests are performed via function calls, which otherwise are called messages: an object passes a message to another. In the preceding example, the object that passed the corresponding set_rating message to the cpp_book object represents the object that we call the set_rating() function in. In this case, we suppose that we call the function from main(), which doesn't actually represent any object at all. We could say it's the global object, the one that operates the main() function, though there is not an entity like that in C++.

We distinguish the objects conceptually rather than physically. That's the main point of thinking in objects. The physical implementation of some concepts of object-oriented programming is not standardized, so we can name the Product struct as a class and claim that cpp_book is an instance of the Product ,and that it has a member function called set_rating(). The C++ implementation almost does the same: it provides syntactically convenient structures (classes, visibility modifiers, inheritance, and so on) and translates them into simple structs with global functions such as set_rating() in the preceding example. Now, let's dive into the details of the C++ object model.

主站蜘蛛池模板: 南投市| 周口市| 太仓市| 凤庆县| 防城港市| 砚山县| 大埔县| 利津县| 东海县| 巴林左旗| 宣威市| 上思县| 德安县| 兴海县| 攀枝花市| 钟祥市| 沂南县| 抚远县| 英超| 颍上县| 靖西县| 台南市| 桓台县| 九台市| 江永县| 洛扎县| 繁峙县| 方正县| 叙永县| 通州区| 喀喇沁旗| 开远市| 叶城县| 浮山县| 沙河市| 洪洞县| 潞城市| 大港区| 囊谦县| 新源县| 沾益县|