Data Structures and Other Objects Using C++ (Chapter 2) 学习笔记五

本文是关于C++学习的笔记,主要聚焦在构造函数的使用,包括构造函数名称与类名相同、无返回值以及声明时的自动调用。此外,还讨论了如何使用命名空间、头文件和实现文件,包括创建命名空间、编写头文件和实现文件的细节。
摘要由CSDN通过智能技术生成

2.2 CONSTRUCTORS

     Constructors are a way to provide an initialization that is guaranteed to be called. A constructor is a member function with these special properties:
  • The name of a constructor must be the same as the name of the class.
  • A constructor does not have any return value. The compiler knows that every constructor has no return value. but a compiler error occurs if you actually write void at the front of the constructor's head.
  • If a class has a constructor, then a constructor is called automatically whenever a variable of the class is declared.
Adding a constructor to the throttle class
     Our throttle constructor has one parameter, which tells the total number of positions that the throttle contains. Here is the prototype for the new constructor, along with its precondition/postcondition contract:
throttle (int size)
// Precondition: 0 < size.
// Postcondition: The throttle has size positions above the shutoff position, 
// and its current position is off

     The constructor's prototype is placed in the throttle class definition along with the other member functions' prototypes, as indicated here:
class throttle
{
public:
     // CONSTRUCTOR
     throttle (int size);
     // MODIFICATION MEMBER FUNCTION
     void shut_off();
...
     Let us see some examples of using the constructor in declarations of throttle objects.
throttle mower_control (4);
throttle apollo (4
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值