cvs.gedasymbols.org/archives/browse.cgi   search  
Mail Archives: djgpp/1997/04/15/22:52:06

Date: Tue, 15 Apr 1997 22:42:30 -0400 (EDT)
From: Michael Phelps <morphine AT hops DOT cs DOT jhu DOT edu>
To: Bryan Murphy <bf461 AT cleveland DOT freenet DOT edu>
cc: djgpp AT delorie DOT com
Subject: Re: Operator == Implementation Question
In-Reply-To: <199704151702.NAA15484@hcst.net>
Message-ID: <Pine.GSO.3.95.970415223829.8604A-100000@hops.cs.jhu.edu>
MIME-Version: 1.0

On Tue, 15 Apr 1997, Bryan Murphy wrote:

> I have a question about operator== for classes.  What is the best method
> for implementing that?   Currently, I have a string called name, and each
> object has an individual name.  I just use that for comparison.  
> 
>        operator == (const OBJECT &object)
>        {
>                    return strcmp(name,object.name) == 0;
>        };
> 
> however, would this work fine for me?  As far as I can tell, it would, and
> it would probably work for all objects (not just ones with names).  Or,
> is there a better way?  I'd rather not give each object a unique name if I
> don't have to. 
> 
> operator == (const OBJECT &object)
> {
> return (this == &object);
> };
> 
> 
This last one won't work.  (You can't take the address of a reference
variable.)  Here is an example program of what I think you want to do:

#include <iostream.h>
#include <string.h>

class	mystringtype
{
	char	*string;
public:
	mystringtype(char *) // constructor
	{
		string = new char[strlen(s)];
		strcpy(string, s);
	}

	~mystringtype() // destructor
	{
		delete[] string;
	}

	bool operator==(const mystringtype& a)
	{
		return (strcmp(this->string, a.string) == 0);
	}
}; // end of class mystringtype

int	main()
{
	mystringtype	a("Hello"), b("Goodbye");

	if (a == b)
		cout << "The strings are equal.\n";
	else
		cout << "The strings are not equal.\n";

	return 0;
}



						---Michael Phelps
						   morphine AT cs DOT jhu DOT edu


                               CH3
                               |
                               N
                             / |
                     ______/   |
                    /      \   CH2
             _____/         \__|__      
           //     \\        /  |  \\     
         //        \\______/___CH2 \\  
          \        /       \       /
           \______/         \_____/
          / ------ \       /      \
        OH           \   /         OH
                       O
 
                   Morphine



- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019