zoukankan      html  css  js  c++  java
  • 类的构造函数(函数重载)

    话不多说,先上代码

    #include<iostream>
    #include<cstring>
    #include<string>
    #include<iomanip>
    #include<fstream>
    using namespace std;
    class Date
    {
    private:
        int year,month,day;
    public:
        Date():year(1),month(1){day=3;};
        Date(int t1,int t2=5,int t3=5);
        void print();
    };
    Date::Date(int s1,int s2,int s3){
    year=s1;
    month=s2;
    day=s3;
    }
    void Date::print()
    {
        cout<<year<<" "<<month<<" "<<day<<endl;
    }

    int main()
    {
        Date w1;
        Date w2(1);
        Date w3(1,2);
        Date w4(1,2,3);
        w1.print();
        w2.print();
        w3.print();
        w4.print();
        return 0;
    }
     

    输出结果:

    1 1  3

    1 5 5

    1 2 5

    1 2 3

    我感觉我已经不适合打代码了,把输出函数打成了 cout<<year<<" "<<month<<" "<<year<<endl;

    我还搁那傻了吧唧的调。。。

    在函数重载的时候有个地方需要注意,如果要初始化三个参数,则必须将Date();这个函数去掉,因为对于全部指定了默认值的构造函数,不能再定义其他参数类型与之相同的重载构造函数。

    #include<iostream>
    #include<cstring>
    #include<string>
    #include<iomanip>
    #include<fstream>
    using namespace std;
    class Date
    {
    private:
        int year,month,day;
    public:
        //Date():year(1),month(1){day=3;};
        Date(int t1=1,int t2=5,int t3=5);
        void print();
    };
    Date::Date(int s1,int s2,int s3){
    year=s1;
    month=s2;
    day=s3;
    }
    void Date::print()
    {
        cout<<year<<" "<<month<<" "<<day<<endl;
    }

    int main()
    {
        Date w1;
        Date w2(1);
        Date w3(1,2);
        Date w4(1,2,3);
        w1.print();
        w2.print();
        w3.print();
        w4.print();
        return 0;
    }
     

    输出结果:

    1 5 5

    1 5 5

    1 2 5

    1 2 3

  • 相关阅读:
    leetcode312 戳气球
    leetcode1283 使结果不超过阈值的最小除数
    软件管理相关命令
    win10+Tensorflow2.1+anaconda python3.7安装
    ResNet残差网络(可以解决梯度消失)
    梯度消失&梯度爆炸(Vanishing/exploding gradients)
    高方差和高偏差
    tf.nn.conv1d
    tensorboard
    卷积
  • 原文地址:https://www.cnblogs.com/letlifestop/p/10262998.html
Copyright © 2011-2022 走看看