I am very unfamiliar with this function and I find the tutorials hard to understand as I'm a newb. Basically in my program I try to avoid the user from entering the same string name (city) twice but also check whether the latitude and longitude are the same (there can be more then one city of the same name on earth but in different locations). I was advised by some to use this code:
bool operator == (const Place &p1, const Place &p2)
{
return !strcmp(p1.name,p2.name) && p1.latitude==p2.latitude && p1.longitude==p2.longitude;
}
To me its unclear where I can put this in my code. I tried putting it straight after I use a function that reads in user input that returns the values into a struct object (Place). the compiler didn't complain when running but I could still enter the same city with the same latitudes and longitudes more then once therefore the code was completely ignored.
Also I was told that the comparison code can't function with variable type double, what about float ? I need decimals to be accurate with geographical points ! thanks in advance
struct Place {
char name[32];
double latitude;
double longitude;
}
booloperator == (const Place &p1, const Place &p2)
{
return !strcmp(p1.name,p2.name) && p1.latitude==p2.latitude && p1.longitude==p2.longitude;
}
int main() {
// your code (including use of ==)
}
operators are just like a special case of a function with a special symbol. You could do the same thing with something like bool compare(const Place &p1, const Place &p2), but == looks better in the code.
Alright so if the the struct is in a seperate file to the main, I should declare the function in the struct file with the code in the block. And in the main file I should include the code within its code block. Well I'm using case statements for each function:1st to display all, 2nd to add a struct using vector (push_back), 3rd to calculate distance, 4th to exit. So I guess I should add the bool operator == in the 2nd case which would look like this:
case 2:
{
Place place = readPlace();
places.push_back(place);
bool operator == (const Place &p1, const Place &p2)
{
return !strcmp(p1.name,p2.name) && p1.latitude==p2.latitude && p1.longitude==p2.longitude;
}
}
Unfortunately I get an error that says function-definition not allowed here before { token