2

I am following this question for iterating over an enum.

enum class COLOR
{
    Blue,
    Red,
    Green,
    Purple,
    First=Blue,
    Last=Purple
};

COLOR operator++( COLOR& x ) { return x = (COLOR)(((int)(x) + 1)); }

COLOR operator*(COLOR c) {return c;}

COLOR begin(COLOR r) {return COLOR::First;}
// end iterator needs to return one past the end!
COLOR end(COLOR r)   {return COLOR(int(COLOR::Last) + 1);}

The problem is that in my project, there are many cpp and hpp files which are compiled separately. It seems the compiler needs to have direct access to implementation of operator++. If I declare in a hpp and then implement in cpp file, I will face with error:

compiler warning: inline function ‘Color operator++(Color&)’ used but never defined

linker error: undefined reference to `operator++(instruction_type&)'

If I define it directly in hpp, I will face with another error

multiple definition of ...

for operator*, begin, and end in linker.

1 Answer 1

2

Adding the inline keyword in front of your 4 functions will allow them to be defined in the header without the multiple definition errors. For example:

inline COLOR operator*(COLOR c) {return c;}

Or you can include just the prototype in the .h file and define the functions in 1 .cpp file.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.