Problems with private variables

Hey guys,

I've been having a problem understanding why I can't write this code the way it is. So I have these class functions with the variables x and y being private and I want to check to see if the user input matches the actual location of a randomized ship. I would just change the variables to public but I'm not allowed to since this is an assignment. Any help would be nice.

~Talemache

1
2
3
4
5
6
 bool compare(Location one, Location two) {
	if (one.x == two.x && one.y == two.y)
		return true;
	else
		return false;
}
Please show the interface of the class Location.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Location {
public:
	Location(); // void constructor, assigns -1 to X coord, and * to Y coord 
	void pick(); // picks a random location
	void fire(); // asks the user to input coordinates of the next shot
	void print() const; // prints location in format "a1"

						// predicate returns true if the two locations match
	friend bool compare(const Location&, const Location&);

private:
	static const int fieldSize = 5; // the field (ocean) is fieldSize X fieldSize
	int x;  // 1 through fieldSize
	char y; // 'a' through fieldSize
};
Compare line 9 of your class declaration with line 1 of your definition. Do you see the differences?

Your prototype at line 9 passes two arguments by const reference. Your function definition says the arguments are passed by value. This is probably going to result in a linker error indicating the proper function definition is undefined.

Also, your function definition is not going to be able to access members of Location, since it is not a friend.
Last edited on
Function overloading. Two standalone predicate functions with name 'compare':
1
2
bool compare(const Location&, const Location&);
bool compare(      Location,        Location );

One has implementation, the other is a friend of class Location.

The compilation stops at compiler error, because the function with implementation is not a friend, but attempts to access private members.

If that function would not exists, then the compilation would stop on linker error due to missing implementation of the friend function.


Accidental overload, I presume?
Ok I see. Thanks guys, I will upload my update in a few hours.

~Talemache
This works so I guess all's well?

~Talemache

1
2
3
4
5
6
bool compare(const Location& one, const Location& two) {
	if (one.x == two.x && one.y == two.y)
		return true;
	else
		return false;
}
Last edited on
Topic archived. No new replies allowed.