• 类构造函数(4)


    /*类构造函数(4)*/

    #include "stdafx.h"
    #include <string.h>
    #include <iostream.h>
    class Date
    {
    public:
        //
    表达式表构造
        Date( int nYear = 1980 , int nMonth = 1, int nDay = 1 )
            :m_nYear(nYear),m_nMonth(nMonth),m_Day(nDay)
        {
           
        }
        int m_nYear;
        int m_nMonth;
        int m_Day;
    };

    class student
    {
    private:
        char m_szName[32];
        int  m_nAge;
        const int  m_nheight;   //
    初始化表初始化
        int& m_refAge;          //
    初始化表初始化
        Date m_BrothDay;        //
    成员对象的构造的选择,自由选择
    public:
        //
    声明时不能带表
        student( int nAge,int nheight,char* pStrName,
            int nYear,int nMonth, int nDay);
        student( char* pStrName );
        student( const student* pObj)
            :m_nheight(pObj->m_nheight),m_refAge(m_nAge)
        {
            cout << "student( const student* pObj)" << endl;
        }
        //
    返回一个引用
        int& GetHeight()
        {
            return (int&)m_nheight;
        }
    };

    //
    实现时可以写初始化表
    //
    初始化表成员赋值顺序无所谓
    //
    数据成员初始化顺序 按照类中声明顺序依次进行
    student::student( int nAge,int nheight,char* pStrName,
                      int nYear,int nMonth, int nDay)
                      :m_nheight(nheight),m_nAge(nAge),m_refAge(m_nAge),m_BrothDay(1979,12)
    {
        strcpy(m_szName,pStrName);
        //m_nAge  = nAge;
        //m_nheight = nheight;
        cout << "student(int,int,char*)" << endl;
    }

    student::student( char* pStrName )
    :m_nAge(25),m_nheight(180),m_refAge(m_nAge),m_BrothDay(1988,12,23)
    {
        strcpy(m_szName,pStrName);
        cout << "student(char*)" << endl;
    }

    int main(int argc, char* argv[])
    {
       
        static student StuStatic("");
       
        //student stu(20,175,"
    张三",1979,12,26);
       
        student stu1("
    张三");
       
        student stu2("
    李四");
       
        cout << &(stu1.GetHeight()) << &(stu2.GetHeight()) << endl;
       
        //
    指针赋值 ,没有构造函数调用
        student *pStu = &StuStatic;
       
        //
    带参构造函数调用  student(const student* pObj)
        //
    类指针作为参数构造
        student Stu3 = pStu;
       
        //
    拷贝构造函数调用
        student Stu4 = *pStu;
       
        return 0;
    }

  • 相关阅读:
    几种滑动验证码处理
    面试题 四 redis线上为什么不能使用 keys *命令
    面试题 六 squid 的理解
    从XP到WIN10,各个系统版本自带 .NET版本整理
    SQL压缩日志
    sql server 使用链接服务器远程查询
    FastReport几个问题
    .Net 三款工作流引擎比较:WWF、netBPM 和 ccflow
    ClientDataSet控件ApplyUpdates的异常触发
    Delphi中关于字符串截取详解
  • 原文地址:https://www.cnblogs.com/w413133157/p/1653611.html
Copyright © 2020-2023  润新知