Archived

This topic is now archived and is closed to further replies.

operator already defined error

This topic is 5129 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I get the following errors in my code, but I can''t understand why: CBody.obj : error LNK2005: "class CVec3 __cdecl operator+(class CVec3 const &,class CVec3 const &)" (??H@YA?AVCVec3@@ABV0@0@Z) already defined in main.obj .. .. .. I get one for each operator that''s defined in the class like this: friend CVec3 operator+ (const CVec3 &v1, const CVec3 &v2); The whole class (including the operator functions) is defined in a header file, which is included by a couple of things, but at the top of the file I have: #ifndef CVEC3_H #define CVEC3_H So it should only include the code once, so I can''t understand why I''m getting the errors. Directly under the class definition I have the operator functions like this: CVec3 operator+ (const CVec3 &v1, const CVec3 &v2) { return CVec3((v1.m_fVec[0] + v2.m_fVec[0]), (v1.m_fVec[1] + v2.m_fVec[1]), (v1.m_fVec[2] + v2.m_fVec[2])); } Any ideas? --------------------------------------- Let''s struggle for our dream of Game! http://andrewporritt.4t.com

Share this post


Link to post
Share on other sites
Header files are only for declaracion and templates.

Having the implementation in the .h file means that any module (read .cpp) that includes the .h will have the implementation in the final object (.obj). That''s why at compile time you''re getting the errors.

Suppose you have cvec3.h declaring class CVec3, you should leave the class declaration there and move the operator+ function to say, cvec3.cpp, and add it to the project.

Share this post


Link to post
Share on other sites
Thanx, thats worked, but one question:

Where I had two operators for * before, so I could have:

Vector * float
OR

float * Vector

Now when I have:

CVec3 operator* (const float &s)
{
return CVec3((m_fVec[0] * s), (m_fVec[1] * s), (m_fVec[2] * s));
}

Does that mean I can only have Vector * float?

---------------------------------------

Let''s struggle for our dream of Game!

http://andrewporritt.4t.com

Share this post


Link to post
Share on other sites
You can put it in a source file as mentioned above, but for this particular case it is not a great idea.

You can define it right in the class where you declare it, or use the keyword ''inline'' before the implementation in the header.

struct CVec3
{
CVec3 operator+(const CVec3& rhs)
{
CVec3 copy(*this)
copy += rhs;
return copy;
}
};

- or -

inline CVec3 operator+(const CVec3& lhs, const CVec3& rhs)
{
CVec3 copy(lhs);
copy += rhs;
return copy;
}

Share this post


Link to post
Share on other sites