类中的模板方法

时间:2019-12-26 15:15:11

标签: c++ function class operator-overloading member

我有一个名为time的类,其中有daymonthyear

我在方法中返回正确的值时遇到问题,在该方法中,根据我们以字符串"s"输入的内容,它应该从这3个字段之一返回一个int值。 / p>

因此,例如,如果我想在日期中获得几天的时间,则应调用函数d["day"]。 我的问题是,这里的代码有问题吗?而且,我应该怎么代替

int operator[] (string s) 
{
    if (s == "day" || s == "month" || s == "year") 
    {
        return ? ? ? ;
    }
}

2 个答案:

答案 0 :(得分:1)

根据说明,如果我理解正确,则需要以下内容。您需要根据字符串匹配返回适当的成员(即daymonthyear)。 (假设您在mDay类中有mMonthmYearint作为Date的同级成员)

int operator[] (std::string const& s) 
{
    if (s == "day")   return mDay;
    if (s == "month") return mMonth;
    if (s == "year")  return mYear;
    // default return
    return -1;
}

或使用switch statement

// provide a enum for day-month-year
enum class DateType{ day, month, year};

int operator[] (DateType type)
{
    switch (type)
    {
    case DateType::day:   return mDay;
    case DateType::month: return mMonth;
    case DateType::year:  return mYear;
    default:              return -1;
    }
}

答案 1 :(得分:1)

一种酒窝方式是将日期定义为三个元素的数组,而不是声明三个单独的数据成员。

在这种情况下,操作员可以按照以下演示程序中所示的方式进行查找。

#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
#include <stdexcept>

class MyDate
{
private:
    unsigned int date[3] = { 26, 12, 2019 };
public:
    unsigned int operator []( const std::string &s ) const
    {
        const char *date_names[] = { "day", "month", "year" };

        auto it = std::find( std::begin( date_names ), std::end( date_names ), s );         
        if (  it == std::end( date_names ) )
        {
            throw std::out_of_range( "Invalid index." );
        }
        else
        {
            return date[std::distance( std::begin( date_names ), it )];
        }
    }
};

int main() 
{
    MyDate date;

    std::cout << date["day"] << '.' << date["month"] << '.' << date["year"] << '\n';

    return 0;
}

程序输出为

26.12.2019

否则,您应该在运算符中使用if-else语句或switch语句。