I want to define a method which can be used by all the classes in my solution, like a global variable but a "global method". I have been reading and the closest concept I found was Static function. Is it the proper solution to what I am looking for? Is there anything better?
And just for the sake of curiosity: why everyone calls it static function?? Shouldn't it be static method since we are in a object-oriented language?
Ok thank you but I am getting some problems compiling. Specifically I am getting a: error LNK2019... it says something about external symbol which cannot be resolved.
I get a link error when I declare a function, but don't define it... Then try to use it.
1 2 3 4
class Frame {
public:
staticvoid hello(); //declaration, but not a definition (see the ;)
};
Try:
1 2 3 4 5
//tell the compiler that hello is a member of Frame
// (note that you only need the keyword "static" when declaring the function)
void Frame::hello() {
cout << "Hello";
}
FYI: you can create a global function that doesn't belong to a class.
It would be smart to put it in a namespace though...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
namespace my_space {
using std::cout;
//hello is now a global function and a member of my_space, full name is my_space::hello
void hello() {
cout << "Hello";
}
}
usingnamespace my_space;
int main() {
hello();
return 0;
}
namespace A {
int n; //because n is defined in namespace A its full name is A::ndouble x; //same here, A::x
}
namespace B {
int n; //you can't have two variables with the same identifier; however
// here because n is being declared inside namespace B its full name is B::n
// which is not the same as the A::n defined above
}
#include <iostream>
//our main function
int main() {
A::n = 10; //in order to refer to are first n (defined in namespace A)
// we need to prefix the variable's name with the namespace's name
// (i.e. used its full name)
A::x = 3.14; //same here
B::n = -1 //we are using a different variable here (the second n, the one from namespace B)
//note that we have to use cout's full name because we omitted the line "using namespace std;"
std::cout << A::n << '\n';
std::cout << A::x << '\n';
std::cout << B::n << '\n';
int n = 7; //here the full name of this variable is n (no prefix)
// because it's declared in the global namespace
std::cout << n << '\n'; //uses the n from the global namespace
// std::cout << x << '\n'; //Error! there is no x in the global namespace
// std::cout << B::x << 'n'; //Error! x is not defined in namespace B
}
Example's output:
10
3.14
-1
7
So by defining your function hello in your own namespace, you ensure that any other hello functions defined will not break your program.