Hello, I was curious as to how I would create some java-static methods and a field. I was led to believe that the correct way to accomplish this was namespaces. If so, could some just explain how these all sort of tie together. Like, which other .cpp files can use my functions, how to declare my namespace, how to define the functions inside it ect...
#include <iostream>
#include <string>
#include <vector>
usingnamespace std;
// Hey, look, just like Java (more or less):
class Hello
{
public:
staticvoid main( vector <string> args )
{
if (args.empty()) args.push_back( "world" );
cout << "Hello " << args[ 0 ] << "!\n";
}
};
// Java does this kind of thing for you behind the scenes:
// (It actually does a number of other important things
// too, but this is all that is needed for this example...)
int main( int argc, char** argv )
{
Hello::main( vector <string> ( argv + 1, argv + argc ) );
return 0;
}
BTW, C++ is not Java. Don't program in C++ as if it were.
Why do you think you need static stuff? Perhaps we can suggest a better way.
What I'm really after is some file pairing (.cpp and .h) (I don't know what to call this yet), such that I can have a field, and a few static methods that will be called from other .cpp files, and those static methods will operate on that field. I do not want to instantiate a class.
A C and C++ header file is the public interface description for all objects (functions, variables, classes, etc) in the corresponding source file (.cpp).
For example, if you have a global int value, say, num_foobars, it must exist in a source .cpp file. But if it is to be made visible to other source files, it must be declared in the header file.
Likewise, any function to be visible to other external files must be declared in the header file.
Awesome. Now, if I wanted to call foobar::incr_foobars() from a completely separate file, do I get this for free without class instantiation? Or must I make these methods static (or does static only work on a file by file basis)? I do have a more specific question to.
Attempting to do something like this:
1 2 3 4 5
std::string path =""; //just have this auto initialized until changed
staticvoid inc_string(std::string inc){
path = path +inc;
}
but I will be calling inc_string from a multitude of places in a multitude of files