LinuxQuestions.org
Download your favorite Linux distribution at LQ ISO.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 11-17-2005, 11:31 AM   #1
lordofring
Member
 
Registered: Feb 2005
Posts: 91

Rep: Reputation: 15
operator== for struct


I have 2 struct variables in a cpp file. I cannot use operator== for the struct.
Code:
#include <stdlib.h>
#include <stdio.h>

typedef struct myStruct_t
{
	int i;
	int j;
};

int main()
{
	myStruct_t a, b;
	a.i = b.i = 2;
	a.j = b.j = 3;

	if (a == b)
	{
		printf("a == b\n");
	}
	else
	{
		printf("a != b\n");
	}
	
	return 0;
}
Does the struct have the default behavior for the operator==?

I compiled it useing "g++ t.cpp" and got the following error message
t.cpp: In function `int main()':
t.cpp:16: error: no match for 'operator==' in 'a == b'

"g++ -v" output:
Reading specs from /usr/lib/gcc/i386-redhat-linux/3.4.2/specs
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --enable-shared --enable-threads=posix --disable-checking --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-java-awt=gtk --host=i386-redhat-linux
Thread model: posix
gcc version 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)


Last edited by lordofring; 11-17-2005 at 11:33 AM.
 
Old 11-17-2005, 04:07 PM   #2
AdaHacker
Member
 
Registered: Oct 2001
Location: Brockport, NY
Distribution: Kubuntu
Posts: 384

Rep: Reputation: 32
My C++ is pretty rusty, but I think the "default behavior" is that the == operator isn't defined for structs. Of course, you can always write one.
Code:
bool operator ==(myStruct_t a, myStruct_t b) {
	return (a.i == b.i) && (a.j == b.j);
}
 
Old 11-17-2005, 06:52 PM   #3
xhi
Senior Member
 
Registered: Mar 2005
Location: USA::Pennsylvania
Distribution: Slackware
Posts: 1,065

Rep: Reputation: 45
exactly, no == is defined for structs... thats a good example from AdaHacker, except you should return int not bool..
IMO, you should use a class here, Im not a big fan of overloading at global level... structs are for data, class is for data and operations on that data which this would qualify as.. I would do somthing like this..

Code:
class Foo
{   
    public:
        Foo(){            
            x=0;
            y=0;
        }
        void setX(int xin){ x=xin; }      
        void setY(int yin){ y=yin; }       
        int getX()const{ return x; }
        int getY()const{ return y; }
        
        int operator==(const Foo& right)const{
            return (x == right.getX()) && (y == right.getY());
        }
        
    private:
        int x;
        int y;
};
 
Old 11-19-2005, 04:05 PM   #4
eddiebaby1023
Member
 
Registered: May 2005
Posts: 378

Rep: Reputation: 33
Or use memcmp to compare the two structs - this has the advantage that you don't need to know the fields in the structures.
Code:
if (memcmp(&a, &b, sizeof(a)))
{
    printf("same\n");
}
else
{
    printf("differ\n");
}
(Not tested, but you get the idea.)
 
Old 11-20-2005, 06:08 PM   #5
lordofring
Member
 
Registered: Feb 2005
Posts: 91

Original Poster
Rep: Reputation: 15
Thanks for everyone's reply.

The reason, that I use the struct instead of the class, is for the public member variables and the light weight. If I use classes, my brain will ask me to write the set()/get() for the variables.

So what's the other difference between the struct and the class. I know all members is public for a struct. Anything elese? Thank you. And I guess a struct must has a default constructor and the default behavior for optertor=. So what's that?
 
Old 11-20-2005, 06:09 PM   #6
lordofring
Member
 
Registered: Feb 2005
Posts: 91

Original Poster
Rep: Reputation: 15
Thanks for everyone's reply.

The reason, that I use the struct instead of the class, is for the public member variables and the light weight. If I use classes, my brain will ask me to write the set()/get() for the variables.

So what's the other difference between the struct and the class. I know all members is public for a struct. Anything else? Thank you. And I guess a struct must has a default constructor and the default behavior for operator=. So what's that?
 
Old 11-20-2005, 06:17 PM   #7
tuxdev
Senior Member
 
Registered: Jul 2005
Distribution: Slackware
Posts: 2,012

Rep: Reputation: 115Reputation: 115
Operator = can be overloaded? That just seems so wrong that it would not be possible period.
 
Old 11-20-2005, 09:06 PM   #8
xhi
Senior Member
 
Registered: Mar 2005
Location: USA::Pennsylvania
Distribution: Slackware
Posts: 1,065

Rep: Reputation: 45
>> So what's the other difference between the struct and the class.

Mainly personal preference.. a *C++* struct and class are not different except for the public/private defaults you have mentioned. Other than that there is nothing that I know of.. Honestly I dont know what the difference in overhead, it would seem like a struct is simpler, and would have less... however they can act identical.. so there may not be a difference...

I use classes because the feel more C++-ey to me.. When I think encapsulation I think class, when I think about defining a simple type like coordinates or somthing, I think struct.. The code that follows is some example.. I knew that in theory there was no difference in the two, but I had never experimented. I killed a few minutes this evening to find out for myself if there were any differences.. And the answer I proved was, no.. atleast not at the level I got to in this example... Check it out.. it does compile as is....

Code:
#include <iostream>

using namespace std;

/*
output
----------
FooBar:: outFooBar()
Bar:: outBar()
Foo:: out()
FooTwo:: outTwo()
Bar:: overloaded comparison
FooBar:: overloaded comaprison
*/

class Foo
{
    public:
        void outFoo(){ cout << "Foo:: out()" << endl; }
};

struct FooTwo
{
    void outTwo(){ cout << "FooTwo:: outTwo()" << endl; }
};

struct Bar : public Foo, public FooTwo
{
    void outBar(){
        cout << "Bar:: outBar()" << endl;
        outFoo();
        outTwo();
    }
    int operator==(const Bar& r) const{
        cout << "Bar:: overloaded comparison" << endl;
        return 0;
    }
};

class FooBar : public Bar
{
    public:
        void outFooBar(){
            cout << "FooBar:: outFooBar()" << endl;
            outBar();
        }
    int operator==(const FooBar& r) const{
        cout << "FooBar:: overloaded comaprison" << endl;
        return 0;
    }
};

int main(int c, char** v)
{
    FooBar fbA = FooBar();
    FooBar fbB = FooBar();
    Bar barA = Bar();
    Bar barB = Bar();

    fbA.outFooBar();  // test all of our print messages....
    barA==barB;     // test that comparison op in the struct
    fbA==fbB;       // ..
    return 0;
}
<edit> removed the virtual function example.. it didnt illustrate what i was thinking quite the way i was thinking it.. maybe next time</edit>

Last edited by xhi; 11-20-2005 at 09:16 PM.
 
Old 11-20-2005, 11:08 PM   #9
Mistro116@yahoo.com
Member
 
Registered: Sep 2005
Posts: 118

Rep: Reputation: 15
Well theres only one thing I would add:

structs are super super helpful in C, but when it comes to C++ as it was stated, its a personal
preference between classes and structs. In C, structs let you have arrays that can be
dynamically allocated and all that good stuff, which you can't do with classes. In C++, its a
lot more flexible, kind of like java.

When you wrote your code, comparing a structure with more than one element using an ==
operator immediately sparked a warning, but I would if you could do it if it was a structure
with just one element. To compare structures, you usually need to write a function that
compares each element of the structure to each element of another true, and then return a
boolean in the case of C++ or an integer denoting true or false (1 or 0) in C.

If you get some time, try a structure with one element using the == operator, id like to see
the results and some people's feedback.

Hope this helps.
Mistro116
 
Old 11-20-2005, 11:50 PM   #10
xhi
Senior Member
 
Registered: Mar 2005
Location: USA::Pennsylvania
Distribution: Slackware
Posts: 1,065

Rep: Reputation: 45
Quote:
To compare structures, you usually need to write a function that
compares each element of the structure to each element of another true, and then return a
boolean in the case of C++ or an integer denoting true or false (1 or 0) in C.
Thats exactly what you are doing with the operator==.. What I found out here is that a *C++* struct and *C* struct are two very different things... While C++ has given the struct the *same abilities* as a class, total encapsulation.. Like you said, in C you are forced to write other functions, as there is no concept of a member function.. I have never tried to put a function ptr into a struct.. maybe you could rig up somthing like that?? that would be some ugly code for sure.. anyhow I made a modification or two on the code...

here is a struct showing the use of the == operator with the multi member value struct.. its like a C struct on steroids
Code:
struct Fooey : public Bar
{
    Fooey():a(5),b(5){}

    // normal compare op you would see for objects
    int operator==(const Fooey& r) const{
        return ((a == r.a) && (b == r.b));
    }

    // illustration only..  very anti intuitive!
    int operator==(int r) const{
        return a==r);
    }
    int a, b;
};

here are a couple extra comparisons for main
Code:
    Fooey fooeyA;
    Fooey fooeyB;

    if(fooeyA==fooeyB) cout << "Fooey A and Fooey B *are* equal" << endl;
    if(fooeyA==5) cout << "The value a in Fooey A is " <<  fooeyA.a << endl;

Last edited by xhi; 11-20-2005 at 11:54 PM.
 
Old 11-21-2005, 12:09 PM   #11
lordofring
Member
 
Registered: Feb 2005
Posts: 91

Original Poster
Rep: Reputation: 15
Quote:
If you get some time, try a structure with one element using the == operator, id like to see
the results and some people's feedback.
I tried this. It's the same as the 2 or more elements.

Summary: In C++, the struct is as same as the class, except that everything is public and no default functions.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
C: Add an operator to a struct drigz Programming 7 09-11-2004 06:44 PM
g++ and wrong struct member addresses / struct size misreporting sonajiso Linux - General 5 05-22-2004 10:16 PM
switch statement converting struct char to struct int oceaneyes2 Programming 2 12-10-2003 04:30 PM
using struct type X as pointer in struct X. worldmagic Programming 1 10-28-2003 02:06 PM
Accessing a struct inside struct cxel91a Programming 1 09-17-2003 04:24 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 07:44 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration