【问题标题】:Would this be considered an Accessor? (C++)这会被视为访问者吗? (C++)
【发布时间】:2014-12-11 02:39:29
【问题描述】:

抱歉,格式很糟糕,但我只是想确定以下内容是否会被视为访问器。

所以我的类定义看起来像这样......

class work {
        public:
           void getInput(); //Mutator
           void output(); //Accessor?
  //...

所以这里的功能..

void work::output()
{
  dayofweek = day + getMonthvalue(month, year) + ....;
  final = dayofweek % 7;

  if(final == 0)
    cout << "The day of the date is Sunday\n";

  else if(final == 1)
    cout << "The day of the date is Monday\n";

  else if(final == 2)
    cout << "The day of the date is Tuesday\n";

  /*.
    .
    .*/

  else {
    cout << "The day of the day is Saturday\n";
  }
}

【问题讨论】:

  • 通常,访问器返回被访问的数据。
  • 通常,mutator 会改变数据成员的值。
  • 我两个都不叫

标签: c++ accessor mutators


【解决方案1】:

您显示为output 的内容通常会写为inserter

class work { 
    // ...

    friend std::ostream &operator<<(std::ostream &os, work const &w) { 
        static char const *names[] = { 
          "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
        };

        return os << names[getDayOfWeek(w)];
    }
};

需要明确一点:inserter 的名称来源于它将某种类型的项插入流中。镜像(从流中获取某种类型的项目)是extractor

如果您真的坚持要为代码使用正确的名称,那么我自己的立场是它是 mistake(强制输出到 cout 会失去灵活性,使用 if 阶梯会使代码丑陋而笨拙)。

【讨论】:

    【解决方案2】:

    一些术语

    • mutator 更改类中的数据。
    • 访问器检索它。

    不,不是真的。 Accessor 派生自访问

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-04
      • 2021-08-07
      • 1970-01-01
      • 2021-05-19
      相关资源
      最近更新 更多