• C++ 面向对象学习2 构造方法


    Date.h

    #ifndef DATE_H
    #define DATE_H
    
    class Date{
    public:
        Date(int d=0,int m=0,int y=0);//自定义了构造方法  会覆盖掉默认的无参构造方法
        void setDay(int d);
        void print();
    private:
        int d;
        int m;
        int y;
    
    };
    #endif

    Date.cpp

    #include "stdafx.h"
    #include <iostream>
    #include "Date.h"
    using namespace std;
    
    Date::Date(int d, int m, int y){
        cout<<"construactor me"<<endl;
        this->d=d;//和java一样 这里也有this  有两种使用方式
        (*this).m=m;
        (*this).y=y;
    }
    
    void Date::setDay(int d){
        this->d=d;
    }
    
    void Date::print(){
        cout<<y<<"-"<<m<<"-"<<d<<endl;
    }

    Test.cpp

    #include "stdafx.h"
    #include "Date.h"
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        //由于我没有显式的写出一个默认的构造方法
        //而且我还自定义了一个自己的构造方法
        //那么自己的构造方法会覆盖掉默认的构造方法的
        
        Date d1;//显示constructor me
        //虽然这里创建对象的时候没有写参数 但是并不是调用的默认无参构造方法
        //因为我为我的构造方法设置了默认值 所以这里可以不给出
        d1.print();
        
        Date d2(5,5,1993);//调用自己的构造方法
        d2.print();//1993-5-5
        return 0;
    }

     =========================================

    Date.h

    #ifndef DATE_H
    #define DATE_H
    
    class Date{
    public:
        Date();
        Date(int d,int m,int y);//自定义了构造方法  会覆盖掉默认的无参构造方法
        void setDay(int d);
        void print();
    private:
        int d;
        int m;
        int y;
    };
    #endif

    Date.cpp

    #include "stdafx.h"
    #include <iostream>
    #include "Date.h"
    using namespace std;
    
    Date::Date(){
        cout<<"constructor me"<<endl;
        this->d=0;
        this->m=0;
        this->y=0;
    }
    
    Date::Date(int d, int m, int y){
        cout<<"construactor me"<<endl;
        this->d=d;//和java一样 这里也有this  有两种使用方式
        (*this).m=m;
        (*this).y=y;
    }
    
    void Date::setDay(int d){
        this->d=d;
    }
    
    void Date::print(){
        cout<<y<<"-"<<m<<"-"<<d<<endl;
    }

    Test

    #include "stdafx.h"
    #include "Date.h"
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        //假如没有自定义自己的构造方法  Date d1就是调用系统默认的无参数构造方法
        //再使用了自己的构造方法的情况下 还想调用无参数的构造方法 就只能再写一个无参数的构造方法
        //当然了 这两个构造方法都是自己的方法
        Date d1;//显示constructor me
        d1.print();//0-0-0
        
        Date d2(5,5,1993);//调用自己的有参构造方法
        d2.print();//1993-5-5
        return 0;
    }
  • 相关阅读:
    数组
    Fiddler抓手机APP包
    APP测试注意点-安装卸载与运行
    【转】查看iOS崩溃日志
    Monkey 命令
    python del 函数
    探索性测试方法
    解决5037端口占用的方法
    App测试Android的闪退总结
    Jenkins邮件配置
  • 原文地址:https://www.cnblogs.com/cart55free99/p/3358253.html
Copyright © 2020-2023  润新知