zoukankan      html  css  js  c++  java
  • 利用 构造函数 实现数据成员的 初始化

     1 //  在程序中  常常需要对    变量进行初始化   在类中怎样 对 对象进行初始化呢?
     2 //  前面说过   类是一种抽象的类型,不占储存空间 , 显然无处容纳 数据  所以在 进行 声明类的时候
     3 //  就 赋初值  是不正确的
     4 //  如果 一个 [[[类中 所有的成员]]] 都是  公用的 则可以在  定义对象时  对数据成员 进行初始化 (  和 结构体的初始化 相似 )
     5 #include<iostream>
     6 using namespace std;
     7 class time              //  声明一个 time 类
     8 {
     9 public:        //  下面的是  公用函数
    10     time();         //定义 构造函数  ,函数名 和  类型名相同
    11     //{
    12         //hour=0;     //  利用构造函数, 对对象 中的数据成员 赋初值           //   虽然出现了  私有函数 中的 内容  但是 只是赋值的话 还是安全的
    13        // minute=0;
    14       //  sec=0;
    15     //}
    16     void set_time();      // 成员函数 声明
    17     void show_time();
    18 private:
    19     int hour;
    20     int minute;
    21     int sec;
    22 };
    23 time::time3
    24 {
    25     hour=0;
    26     minute=0;
    27     sec=0;
    28 }
    29 void time::set_time()   //  定义成员函数
    30 {
    31     cin>>hour;
    32     cin>>minute;
    33     cin>>sec;
    34 }
    35 void time::show_time()
    36 {
    37     cout<<hour<<":"<<minute<<":"<<sec<<endl;
    38 }
    39 int main()
    40 {
    41     time t1;
    42     t1.set_time();
    43     t1.show_time();
    44     time t2;
    45     t2.show_time();
    46     return 0;
    47 }
    48 /*C++ 提供了构造函数 来处理 对戏那个的初始化  构造函数 是一种特殊的成员函数 ,与其他的成员函数 不同 ,不需要 用户来 调用他 而是在 建立对象时 自动执行
    49 构造函数 的名字必须和类型名 相同 而且不能任意命名 . 它 不具有任何的类型  ,不返回 任何值
    50 */
    51 
    52 
    53 // 在 类中 我们定义了 构造函数  在 以后 建立 对象的时候 会 自动执行 构造函数
     1 #include<iostream>
     2 using namespace std;
     3 class box
     4 {
     5 public:
     6     box(int ,int ,int );        //声明 带参的构造函数 
     7     int volume();         //声明计算体积的函数
     8 private:
     9     int height;
    10     int width;
    11     int  length;
    12 };
    13 box::box(int h,int w,int len)   // 类外 进行定义 带参的构造函数 
    14 {
    15     height=h;
    16     width=w;
    17     length=len;
    18 }
    19 int box::volume()     //  计算体积 
    20 {
    21     return (height*width*length);
    22 }
    23 int main()
    24 {
    25     box box1(12,25,30);
    26     cout<<box1.volume()<<endl;
    27     box box2(15,30,21);
    28     cout<<box2.volume()<<endl;
    29 }
  • 相关阅读:
    prototype.js超强的javascript类库
    MySQL Server Architecture
    Know more about RBA redo block address
    MySQL无处不在
    利用Oracle Enterprise Manager Cloud Control 12c创建DataGuard Standby
    LAMP Stack
    9i中DG remote archive可能导致Primary Database挂起
    Oracle数据库升级与补丁
    Oracle为何会发生归档日志archivelog大小远小于联机重做日志online redo log size的情况?
    Oracle Ksplice如何工作?How does Ksplice work?
  • 原文地址:https://www.cnblogs.com/A-FM/p/5227566.html
Copyright © 2011-2022 走看看