zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    Django(二)
    VSCode写Django的坑
    AXF—个Django项目
    Linux
    安装软件方面的问题及解决方法杂烩
    Python
    环境搭建
    Django(一)
    关于excel表
    (十)selenium实现微博高级搜索信息爬取
  • 原文地址:https://www.cnblogs.com/cart55free99/p/3358253.html
Copyright © 2011-2022 走看看