Skip to main content
gamedev.net
🔒 Locked

operator already defined error

Started by wasd Nov 28, 2003 at 11:03 AM 2 replies 1.6k views
Original Post
wasd
wasd
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
crypticmind
crypticmind
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.
wasd
wasd
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
Shannon Barber
Shannon Barber
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;
}
The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.