[sclug] Using an enum as a method return type in C++

Paul Vanlint paul at polyzing.com
Sat Oct 25 09:05:37 UTC 2003


There were two problems with using the enum with your code Tim

1) The enum was private and thus if it was returned as a type, the
calling code wouldn't understand how to use the type. All return types
of public functions must be public too.

2) The enum is defined with the class, therefore to access it you need
to specify the class as the namespace, e.g. Test::weekday or Test::mon

Also, you defined the function to return a const weekday enum, but I
suspect you meant to define the function as a const member function. In
that case, the const keyword must go at the end of the definition.

Here is a modified version showing the modified code at work.

I hope this helps. BTW, I compiled this with gcc 3.2 using "gcc test.cc
-lstdc++ -o test"

Regards,

Paul.



// Test.cc
#include <iostream>

class Test
{
  public:
    enum weekday {mon, tue, wed,thurs, fri};
    Test();
    ~Test();
    virtual void setday( const weekday _newVal);
    virtual weekday getday() const;
    friend std::ostream& operator<<(std::ostream& stream, Test t);

  private:
    weekday day;

};

std::ostream& operator<<(std::ostream& stream, Test t);


Test::Test()
{
  day = mon;
}

Test::~Test()
{
}

Test::weekday Test::getday() const
{
  return day;
}
void Test::setday( const weekday _newVal)
{
  day = _newVal;
}

std::ostream& operator<<(std::ostream& stream, Test t)
{
  switch (t.day)
  {
          case Test::mon: std::cout << "Monday"; break;
          case Test::tue: std::cout << "Tuesday"; break;
          case Test::wed: std::cout << "Wednesday"; break;
          case Test::thurs: std::cout << "Thursday"; break;
          case Test::fri: std::cout << "Friday"; break;
          default: std::cout << "Unknown"; break;
  }
  std::cout << std::endl;
}

int main()
{
  Test a;

  Test::weekday tmp_day = a.getday();
  a.setday(Test::wed);
  std::cout << a;
  a.setday(tmp_day);
  std::cout << a;
  return 0;
}






More information about the Sclug mailing list