Click to See Complete Forum and Search --> : overload <= operator
ravash5000
October 24th, 2001, 06:14 PM
I am trying to overload <= 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 <=(name& A, name& B)
{
return true;
}
int main()
{
name A, B;
if (A <= B) cout << "Hi;";
return 0;
}
Please help.
DrNeoCortex
October 24th, 2001, 07:31 PM
well first of all, if you define the "operator <=" outside a class, you have to precede it with "ClassName::". also there's only one parameter into "operator <=" the other parameter is the Name object itself, or the "this" object. take a look at this small example. it overloads the "<=" operator to base the comparison off the length of the strings, not the characters:
#include <iostream.h>
#include <string.h>
class Name
{
public:
Name(char *c)
{
strcpy (m_name, c);
}
operator <= (Name &a)
{
return strlen(m_name) <= strlen(a.m_name);
}
private:
char m_name[64];
};
void main()
{
Name n("abcdefg");
Name m("h");
if (n <= m)
{
cout << "abcdefg <= h" << endl;
}
else
{
cout << "abcdefg > h" << 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<=(name& A, name& B)
{
return true;
}
int main()
{
name A, B;
if (A <= B) cout << "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.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.