|
-
June 13th, 2002, 10:47 AM
#1
Comparison Operator Overloading
I have created a class for which I would like to overload the == operator. The name of the class is String. The problem I am running into comes into play when the object is a pointer..
String *a = new String();
if (a == "") return true; //error in VC++
the following operators are defined in the string class..
class String
{
bool operator ==(char *);
friend bool operator==(String &, char *);
}
I tried adding:
friend bool operator==(String *, char *);
but I get a compiler error.. What to do?
-
June 13th, 2002, 11:26 AM
#2
I hope this is just an academic exercise, since C++ has a string class already. No need to be reinventing the wheel.
Anyway, the "" is a const char *, not a char *. Maybe that's your problem -- you need to overload for const char *. It would also help if you post the compiler error.
Regards,
Paul McKenzie
-
June 13th, 2002, 12:15 PM
#3
Try this code. It is not complete String class, it just show the usage of == operator. In fact you dont need to make more than one overloaded function for == function operator for operator overloading if you are not using explicit with your ctor.
Code:
#include <iostream>
using namespace std;
class String
{
private:
char* mData;
public:
// default ctor
String(char* pData = "")
{
mData = new char[strlen(pData) + 1];
strcpy(mData, pData);
}
// copy ctor
String(const String& pString)
{
delete [] mData;
mData = new char[strlen(pString.mData) + 1];
strcpy(mData, pString.mData);
}
// assingment operator
String& operator = (const String& pString)
{
delete [] mData;
mData = new char[strlen(pString.mData) + 1];
strcpy(mData, pString.mData);
return *this;
}
// equal operator
friend bool operator == (const String& rhs, const String& lhs)
{
return strcmp(rhs.mData, lhs.mData) == 0 ? true : false;
}
// dtor
~String()
{
delete [] mData;
}
};
int main()
{
String str = "Hello";
if (str == "")
{
cout << "Empty" << endl;
}
else if (str == "Hello")
{
cout << "Hello world" << endl;
}
else
{
cout << "Bye world" << endl;
}
return 0;
}
Hope it helps.
-
June 13th, 2002, 12:55 PM
#4
String\iswa\iswa.cpp(14): error C2665: 'operator`=='' : none of the 2 overloads can convert parameter 1 from type 'String *'
if I try to call the operator directly this is the error I get. It's looking for operator ==(String *, char *) but I can't put String * in the operator because I get this error:
String.h(36): error C2803: 'operator ==' must have at least one formal parameter of class type
adding const anywhere does not help.
Last edited by _illusioned; June 13th, 2002 at 01:03 PM.
-
June 13th, 2002, 01:38 PM
#5
Can you provide a sample of how your are calling it. If your code looks like:
String *s = new String("Hello");
if (s == "hello")
{
}
then it should be
if ((*s) == "hello")
{
}
then the overloads will be proper.
-
June 13th, 2002, 01:46 PM
#6
That is what i'm trying not to have in my code.. Isn't there any way to compare without first deferencing the ptr?
Isn't there a way to say..
String *a = new String();
if (a=="ADSDSA")
without having to put:
if (*a == "ADSDSA")
??
-
June 13th, 2002, 01:48 PM
#7
When you use operator==, it has to be on an object, not on a pointer to an object. You need to dereference the pointer in order to compare the object. Otherwise, you are trying to compare the pointers, which won't work as there is no conversion between a String * and a char *.
So, using your original code, you need to do the following:
String *a = new String();
if ( *a == "" ) return true; // dereference a
Best regards,
John
-
June 13th, 2002, 03:59 PM
#8
Even better is
String s("Hello");
if (s == "hello")
{
}
Very little reason to use pointers with strings.
Jeff
-
June 13th, 2002, 05:44 PM
#9
Originally posted by _illusioned
That is what i'm trying not to have in my code.. Isn't there any way to compare without first deferencing the ptr?
Isn't there a way to say..
String *a = new String();
if (a=="ADSDSA")
without having to put:
if (*a == "ADSDSA")
??
Comparing two strings for equality requires you to test each character until a difference is found or one string terminates before the other. This is the case for char array functions such as strcmp(), and it is also the case for std::string (but this is hidden from you). Therefore you're not buying anything by specifying a (String *, char *) overload, so just stick with the one that takes a String. You have to dereference the string anyway to do the comparison, so your overload of (String *,...) really adds nothing, except maybe confusion to any other programmer trying to maintain your code. A pointer is supposed to have "pointer-like" semantics. A pointer shouldn't be taking on "a life of its own" by magically deferencing itself and doing comparisons (unless it is a smart pointer, but even in this case, it acts like a pointer).
Also, excessive overloading should be avoided. What happens is that if you excessively use overloading, the compiler will invariably come up with "ambiguous" function call errors, and worse, may not flag you for a compile error but will make erroneous and/or unoptimal conversions behind your back at runtime.
Regards,
Paul McKenzie
-
June 13th, 2002, 07:16 PM
#10
Using operator == for string comparison is BAD
It is a BAD idea to use == operator for string comparison. The reason is obvious:
if (mystring == "hello world!") {//...}
Why it is bad? There is ambiguity exactly what do you mean two strings are "equal"? It is unfortunate that alphabets of most languages have lower case and upper case. When comparing two strings, some times case doesn't matter, some times you do care about the case. Using a "==" buries that information and leaves ambiguity there.
It is better to use traditional strcmp, stricmp, strncmp etc.
-
June 13th, 2002, 09:56 PM
#11
Re: Using operator == for string comparison is BAD
Originally posted by Anthony Mai
It is a BAD idea to use == operator for string comparison. The reason is obvious:
if (mystring == "hello world!") {//...}
Why it is bad? There is ambiguity exactly what do you mean two strings are "equal"?
The ambiguity is when someone is creating home-made classes and there is no written rules as to what is meant by "==".
For std::string, operator == is well defined -- the comparison is done lexicographically according to the current character traits ("The C++ Standard Library", Josuttis, 11.2.7).
Regards,
Paul McKenzie
-
June 14th, 2002, 01:05 AM
#12
You can not use pointer and avoid dereferncing, becouse
pointer is predefined type, like int or double.
All necessary operators for these types are already defined and can not be overloaded
-
June 14th, 2002, 09:59 AM
#13
What exactly is meant by lexicographically comparison? Is it dictionary order? If it is dictionary order then you are talking about "==" as case-insensitive comparison, because dictionaries never list the same word in different cases.
In real life you have both case-sensitive string comparison and case-insensitive ones. And operator== is just one. There is no way you can fit one shoe on both left and right foot. So you have to use something other than operator== at least under some situation. For the sake of avoiding confusion it is best to abandon operator== altogether and use strcmp() and stricmp().
And what about Hebrew? Hebrew is written from right to left, how does operator== work in this case?
When a symbol like "operator==" could represent too many different things, it no longer carries any useful information of what it is and becomes less and less useful. If half of the world has a first name Paul. I would have to wouder who exactly is Paul. It's better to use something that uniquely identify what it is.
-
June 14th, 2002, 10:21 AM
#14
Agreeing with all who recomment against using "==" for the same reasons, but I have two points.
1) If you dont want peoplt to use it, implement it privately, so they dont use accidently use a comipler generated one.
2) Much prefer using member/frend functions like CompareNoCase, CompareCase than older "c" library style routines.
-
June 14th, 2002, 10:35 AM
#15
Sounds kind of like the reasons the people who created Java gave when they decided against operator overloading.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|