获取“获取”其他获取功能的功能

时间:2019-04-23 15:31:46

标签: c++ get

所以我的挑战是:创建一个从其他get函数接收所有参数的函数,例如:

int get_day() const {return day;}
int get_month() const {return month;}
int get_year() const {return year;}

我希望get_date()能够收到以上所有内容。我怎样才能做到这一点?例如:

int get_date() const {
   get_day();
   get_month();
   get_year();
}

3 个答案:

答案 0 :(得分:2)

您可以像这样打包日期:

int get_date() const {
    return get_day() + 100 * get_month() + 10000 * get_year();
}

请注意,这只是整数,看起来像日期。如果您打印今天的日期,它将是数字20190423,也就是数字20,190,423。

答案 1 :(得分:1)

正如我在评论中提到的那样,当您需要函数返回3个int时,返回单个int是没有意义的。 只需返回一个这样的数组:

#include <iostream>
#include <array>

struct Cal
{
    typedef std::array<int,3> Date;

    int day = 13;
    int month = 7;
    int year = 2019;

    int getDay() const
    {
        return day;
    }
    int getMonth() const
    {
        return month;
    }
    int getYear() const
    {
        return year;
    }

    Date getDate() const
    {
        return {{getDay(),getMonth(),getYear()}};
    }
};


int main()
{
    Cal c;

    for (auto &&i : c.getDate())
        std::cout<< i <<" ";
    std::cout<<std::endl;
}

代码输出:

13 7 2019 

此外,最好仅返回实际成员而不是调用getter函数。除了getDate()函数也是该类的成员。

Date getDate() const
{
    return {{day,month,year}};
}

在线代码示例:https://rextester.com/WPXX24681

答案 2 :(得分:1)

您可以在以下位置使用tm struct:std::tm

student with 100 is Rajiv who is in class: 10 and he is of PCMC stream
student with 101 is Sam who is in class: 11 and he is of PCMB stream
student with 102 is Ghanshyam who is in class: 12 and he is of commerce stream
student with undefined is undefined who is in class: undefined and he is of undefined stream

不要重新发明轮子