首页 > 解决方案 > 类中的模板方法

问题描述

我有一个名为的类time,它有day,monthyear.

我在我的方法中返回正确的值时遇到问题,它在哪里,取决于我们作为字符串输入的内容,"s"它应该int从这 3 个字段之一返回一个值。

因此,例如,如果我想在我的日期中获取天数,我应该调用该函数d["day"]。我的问题是,我的代码有问题吗?而且,我应该放什么而不是

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

标签: c++functionclassoperator-overloadingmember

解决方案


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

在这种情况下,操作员可以查看以下方式,如下面的演示程序所示。

#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 语句。


推荐阅读