类的构造函数和析构函数 Class Constructors and Destructors

来源:互联网 发布:网络空间研究院 编辑:程序博客网 时间:2024/06/06 05:00

首先要说明,这两个字中国人是乱翻译的,像这样的翻译还有很多,估计哪个砖家喝高了,duang 一下,就翻译成这样了

socket 套接字

handle 句柄

instance 实例


字典上constructor 是这样翻译的:

我是查的朗文词典 没有constructor ,只有construct  加or  就是做这个的人  ,初中老师是这样教我的

construct 1, to build a large building, bridge, road etc 构筑,建造

                2, an idea formed by combining pieces of knowledge 构想, 概念

                3, formal something that is built or made  [正式]建造物; 构成物


collins 的翻译也差不多

               1 , If you construct something such as building, road, or machine, you build it or make it

                2, If you construct something such as an idea, a piece of writing, or a system, you create it by putting different parts together


destruction 1 Destruction is the act of destroying something, or the state of being destroyed              //  摘自collins

                   2 the act or process of destroying something   破坏                                                           // 摘自朗文



看完翻译, construct 就是build 或者make 的意思

                   destruct   就是 destroy 的意思


本来很简单的两个词,硬是被翻译得看不懂了。



进入正题

我们先定义一个class

// stock00.h -- Stock class interface// version 00#ifndef STOCK00_H_#define STOCK00_H_#include <string>class Stock // class declaration{private:    std::string company;    long shares;    double shar_val;    double total_val;    void set_tot() { total_val = shares * share_val; }public:    void acquire(const std::string & co, long n, double pr);    void buy(long num, double price);    void sell(long num, double price);    void update(double price);    void show();};    // note semicolon at the end


对于一个class来说,constructor 和 Destructor 某种程度是需要标准配备的, 下面我们一起讨论哈

为什么需要它们以及怎么去实现它们。

在C++里面,可以像使用标准类型(standard types) 一样去使用class object.

但是在初始化部分,还是有区别的

int year = 2001;     //可以这样玩struct thing{    char *pn;    int m;};thing amabob = {"wodget", -23};   //同样是可以的Stock hot = { "Sukie's Autos, Inc.", 200, 50.25};   //  不准这样玩


    你不能这样去初始化一个Stock , 因为在Stock里面,有private 类型,也就是说,这种数据成员,函数是不能直接去

访问的。想访问这样的类型,唯一的办法是通过成员函数。那就是说,如果你想成功的去初始化一个object,那么你需要一个合适的成员函数,(当然,你可以把里面的private 成员改为public, 但是这样做,就违背了做用class的初衷: 数据隐藏.)


   一般来说,最好所有的object在创建的时候,就被初始化好。比如, 看看下面的code.

Stock gift;gift.buy(10, 24.75);


对于当前Stock 类的实现, 我们没有给它的company 成员一个值。

如果要这样用,我们只能假设用户在调用任何成员函数之前去调用  acruire() 函数。

但是这种假设是没法保证一定成立的。为了解决这个问题, C++ 提供了一种特殊的成员函数,叫做class constructor.

用来构建新的object 以及给它的成员赋值。









0 0
原创粉丝点击