Operator Overloading Failure

Currently my program is compiling, but it shuts down after that. What I am trying to accomplish is to compare two classes items to determine if they are the same. i.e "is myClass.info == hisClass.info?" but also to only let the template work for comparing class items not integers or strings. lets just say either the template should work for comparing only class items or, it should work for comparing any of the three.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//overloading
template<class T>
bool operator== (const T& a, const T& b)
{
  return (a == b);
}

//Template for determining the set that occurs the most. works on data types supporting operator<
template<class T>
int findMost(T arr[], int total)
{
    int maximum=1; //count of: the type that occurs the most
    int count=1;
    int position=0; //positionition

    for(int i=0; i<total; ++i)
    {
       if(arr[i] == arr[i+1]) // <-- how do i compare the two struct items here
         count++;
       else
       {
         if(count == maximum)
         {
           if(min(arr[i],arr[position]) < arr[i])
             position=i;
         }
         else if(count>maximum)
         {
           maximum=count;
           position=i;
         }
         count=1;
       }
    }
    return position;
}


//cpp file... here i make an array of a certain structs, which each will have a member that contains a string, 

  string* mystring = new string[argc];
  myStruct* arr = new myStruct[argc];
  

  for (int i = 0; i < argc-1; ++i)
    {
      mystring[i] = argv[i+1];
      arr[i] = myStruct(mystring[i]);
    }

....sort arr
...
...
int number = findMost(arr, total);
Last edited on
That == operator looks like infinite recursion to me...
is there a way to better compare structs using operator overloading and tell if they are equal, im new to overloading.
Last edited on
Well the whole point is that you define what the operator does. The goal is to make it intuitive, by comparing what the class represents, rather than comparing just the raw data (although sometimes you want to compare just the raw data).

FOR EXAMPLE

A string class wouldn't compare things like the amount of memory allocated, or the pointer to the data. It would compare the actual string data.

A fraction clas wouldn't just compare numerators and denominators, it would find the GCD and compare to see if the represented numbers are equivilent (ie: 1/3 == 2/6)

So ask yourself... "what does myStruct represent", then write an == operator which compares based on what it represents.

If it just represents a clump of data, then it might be just comparing each individual member.


EDIT:

also, this was weird:

if(min(arr[i],arr[position]) < arr[i])

that's a very roundabout way of doing this:

if(arr[position] < arr[i])
Last edited on
Topic archived. No new replies allowed.