![Quote](https://cboard.cprogramming.com/images/misc/quote_icon.png)
Originally Posted by
Roger
I would like to write a 'global function' that is *outside* of the class. This function should be able to work with two different objects. Here's what I tried (it does not compile):
The problem is that you declared the function with SomeClass parameters, but SomeClass has not yet been declared. You could fix this with a forward declaration:
Code:
class SomeClass;
int someGlobalFunction(SomeClass x, SomeClass y);
or you could simply declare someGlobalFunction after defining SomeClass, since a class definition is also a class declaration.
Given what you appear to be doing, this is one way of doing it:
Code:
#include <cstdio>
class SomeClass {
public:
SomeClass(int x, int y, int z) : x(x), y(y), z(z) {}
int getX() const;
int getY() const;
int getZ() const;
private:
int x;
int y;
int z;
};
void print(const SomeClass& obj);
int someGlobalFunction(const SomeClass& x, const SomeClass& y);
int main() {
SomeClass a(1, 2, 3);
SomeClass b(4, 5, 6);
print(a);
print(b);
}
void print(const SomeClass& obj)
{
std::printf("%d %d %d\n", obj.getX(), obj.getY(), obj.getZ());
}
int someGlobalFunction(const SomeClass& a, const SomeClass& b) {
return a.getX() + b.getY + b.getZ();
}
// ...
Notice that I have:
- Included <cstdio> instead of <stdio.h>
- Used a constructor initialisation list instead of assigning in the constructor body.
- Declared the public members of the class before the private members.
- Added in the missing declarations for getX() etc.
- Changed print to be a free function since it can use the getter functions.
- Pass SomeClass by const reference instead of by value since you do not actually need to copy.
- Shifted the declaration of someGlobalFunction to after the class definition.
My indentation is more consistent than yours too ![Smile](https://cboard.cprogramming.com/images/smilies/smile.png)
You should add in the getter function definitions and fix the compile errors that result.