Click to See Complete Forum and Search --> : overload <= operator


ravash5000
October 24th, 2001, 06:14 PM
I am trying to overload &lt;= operator, her is the code that I am using, the linker generated an error saying: one or more multiply defined symbols have been found. Here is the code:

bool operator &lt;=(name& A, name& B)
{

return true;
}
int main()
{
name A, B;
if (A &lt;= B) cout &lt;&lt; "Hi;";
return 0;
}



Please help.

DrNeoCortex
October 24th, 2001, 07:31 PM
well first of all, if you define the "operator &lt;=" outside a class, you have to precede it with "ClassName::". also there's only one parameter into "operator &lt;=" the other parameter is the Name object itself, or the "this" object. take a look at this small example. it overloads the "&lt;=" operator to base the comparison off the length of the strings, not the characters:


#include &lt;iostream.h&gt;
#include &lt;string.h&gt;

class Name
{
public:
Name(char *c)
{
strcpy (m_name, c);
}

operator &lt;= (Name &a)
{
return strlen(m_name) &lt;= strlen(a.m_name);
}

private:
char m_name[64];
};

void main()
{
Name n("abcdefg");
Name m("h");

if (n &lt;= m)
{
cout &lt;&lt; "abcdefg &lt;= h" &lt;&lt; endl;
}
else
{
cout &lt;&lt; "abcdefg &gt; h" &lt;&lt; endl;
}
}

easye21
October 24th, 2001, 10:00 PM
All you should have to do is put is
#include name.h or whatever file contains the class name. You don't have to put name:: because its a global function.

James Curran
October 26th, 2001, 03:18 PM
Your problem lies elsewhere. The following compiles & runs fine for me (VC6SP5)class name {};

bool operator&lt;=(name& A, name& B)
{
return true;
}

int main()
{
name A, B;
if (A &lt;= B) cout &lt;&lt; "Hi;";
return 0;
}





Truth,
James
http://www.NJTheater.com
http://www.NovelTheory.com
I don't do it for the points (OK, maybe I do), but rating a post is a good way for me to know if I helped.

James Curran
October 26th, 2001, 03:28 PM
Your first paragraph is incorrect. You may defined a global (non-member) binary operator function. Often, that is the *prefered* way to define an operator overload.

Truth,
James
http://www.NJTheater.com
http://www.NovelTheory.com
I don't do it for the points (OK, maybe I do), but rating a post is a good way for me to know if I helped.