在类外部创建枚举类型函数的定义,并在枚举类型

时间:2017-03-02 18:04:41

标签: c++ enums

我在类外部创建枚举类型函数的定义并且在枚举类型上运算符重载时遇到了一些错误。我在下面放置代码。

  1. 以前我在类范围之外的函数定义中遇到错误:'Month' does not name a typeMonth Date::int_to_month(int x){ // function body } 我发现Date::Month符号是可以接受的。我的问题是,为什么我们使用这种表示法?这样做还有其他可能吗?
  2. 现在第二个问题。我试图在enum Month上重载++运算符。

    我收到的构建消息:

    1. postfix 'Date::Month Date::operator++(Date::Month&)' must take 'int' as an argument。我不明白,问题出在哪里以及我为什么不能超载。
    2. 代码:

          class Date
          {
          public:
          enum Month{
              jan=1,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec
          };
      
          Date(int yy, Month mm, int dd);
      
          Month int_to_month(int x);
      
          Month operator++(Month& m);
      
          private:
          int y;
          Month m;
          int d;
          };
      
          Date::Date(int yy, Month mm, int dd)
           :y(yy),m(mm),d(dd)
          {
      
          }
      
          Date::Month Date::int_to_month(int x)
          {
          if (x<jan || dec<x) error("bad month");
          return Month(x);
          }
      
          Date::Month Date::operator++(Month& m)
          {
          if(m==dec)? jan:Month(m+1);
          return m;
          }
      

      PS。感谢所有的答案和努力:)

2 个答案:

答案 0 :(得分:0)

  1. 由于Month的范围仅限于班级Date,您必须使用Date::Month。如果您有另一个名为Month的枚举,那么它值得做。

  2. operator++可以通过四种不同的方式重载 - 后缀/前缀,内部/外部类定义。他们的典型签名是:

    T& T::operator++(); //prefix, inside class definition
    T& operator++(T& a); //prefix, outside class definition
    T T::operator++(int); //postfix, inside class definition
    T operator++(T& a, int); //postfix, outside class defintion
    
  3. 您可以返回任何想要的内容,但这些内容通常都是使用返回值。

    在您的示例中,您在类内部重载operator++,但在类版本之外指定参数。在类的内部没有aguments或int,如果你已经给它一些参数,你的编译器期望int

    第二件事是你的身体超负荷operator++没有多大意义。它应该增加成员m但返回不增加的值。

    Date::Month Date::operator++(int)
    {
        Month ret = m;
    
        //if you find ternary operator more readable...
        m = (m == Month::dec ? Month::jan : Month(m + 1)); 
    
        return ret;
    }
    

答案 1 :(得分:0)

重载operator++的后缀版本需要使用该语言的解决方法,以便将其与其他名称相同的前缀版本区分开来;你必须传递一个未使用的int参数:

Month operator++(int);

然后是这一行,您似乎将if?:混合在一起。这没有用:

if(m==dec)? jan:Month(m+1);

成功:

Date::Month Date::operator++(int)
{
    if (m == dec)
    {
        return jan;
    }
    else
    {
        return Month(m + 1);
    }
}

这可以帮助你解决最基本的麻烦。