Ivan Font
Ivan Font

Reputation: 73

C++ "Class Enum" Novice Problems

I'm starting learning to code in C++ (coming from VB.net) and i need some help in enum class usage.

I've done this simple code from a lerning exercise (originally divided in header.h and Exercise.cpp, but i putted it all together here):

#include <iostream>
#include <string>

#define BEGIN_WITH(x) { \
        auto &_ = x;
#define END_WITH() }

using namespace std;

enum class Gender { Male, Female };

struct PersonStruct {
    string _Name;
    string _SurName;
    int _Age;
    double _Heigth;
    Gender _Gender; };

class Person { public:
    string _Name{};
    string _SurName{};
    int _Age{};
    double _Heigth{};
    Gender _Gender{}; };


int ModifyPerson(Person& PassPersona, PersonStruct Attribute) {
    PassPersona._Name = Attribute._Name;
    PassPersona._SurName = Attribute._SurName;
    PassPersona._Heigth = Attribute._Heigth;
    PassPersona._Age = Attribute._Age;
    PassPersona._Gender = Attribute._Gender;

    return(0); }

int main() {    Person TestingPerson;

    BEGIN_WITH(TestingPerson)
    _._Age = 23;
    _._Gender = Gender::Male;
    _._Heigth = 1.94;
    _._Name = "John";
    _._SurName = "Smith";
    END_WITH()

    cout << "Person attributes: " << endl;
    cout << "Name: " << TestingPerson._Name << endl;
    cout << "Surname: " << TestingPerson._SurName << endl;
    cout << "Age: " << TestingPerson._Age << endl;
    cout << "Gender: " << TestingPerson._Gender << endl;
    cout << "Heigth: " << TestingPerson._Heigth << endl;
    cout << endl;

    ModifyPerson(TestingPerson, PersonStruct{ "Poca","Hontas",24,1.85,Gender::Female });

    cout << "New Person attributes: " << endl;
    cout << "Name: " << TestingPerson._Name << endl;
    cout << "Surname: " << TestingPerson._SurName << endl;
    cout << "Age: " << TestingPerson._Age << endl;
    cout << "Gender: " << TestingPerson._Gender << endl;
    cout << "Heigth: " << TestingPerson._Heigth << endl;

    return(0); }

I've made the structure in order to group all Person class parameters. Doing this i've learned that using enum class is more secure than class. But when i switched to enum class a lot of errors prompted on my code. I've solved almost all of them, except this:

cout << "Gender: " << TestingPerson._Gender << endl;

Error code E0349 "no operator "<<" matches these operands"

I've searched around but i find no solution to this. Thanks in advance for your time! (any suggestion or recommendation on my code should be appreciated)

Upvotes: 0

Views: 221

Answers (1)

Roy2511
Roy2511

Reputation: 1048

<< operator is not defined for class Gender because it's your own class. You'll need to overload it. More info here.

enum class Gender
{
  male,
  female
};

ostream& operator<< (ostream & os, const Gender & g)
{
  switch(g)
  {
      case Gender::male: os << "Male"; return os;
      case Gender::female: os << "Female"; return os;
  }
  return os;
};

Upvotes: 2

Related Questions