Reputation: 31
How would I go about making static methods that are used like the static methods in java when I have multiple .cpp files?
In java you can reference another class by using MyClass name = new MyClass(); and every variable in this class will be the same when called in any other file that you have.
I seems like a pain to have to be able to pass by reference the MyClass& name in every function you want to use that class in.
Is there a way to define MyClass name at the top of a .cpp file without it making a brand new instance of that object in memory and wiping away all of your progress, for example if you were trying to make a simple counter, and the main class would tell the counting class to increment, and the visibility class would get the number of counts from the counting class and print it to the screen. Now this would be simple in that you could pass the counting class to the visibility, but what if you had 20+ methods, then it would be difficult to keep track of.
I'm just not that familiar with static, or references, and I have looked around and saw "namespace", but I am not sure where I would define this, or if it is what I even need.
Thanks in advance
Example Java Code:
public class Foo{
private static int counter = 0;
public int getCounter(){
return counter;
}
public void incrCounter(){
counter+=1;
}
}
public class MainProg{
public static void main(String[] args){
Foo foo = new Foo();
Display disp = new Display();
foo.incrCounter();
foo.incrCounter();
disp.displayCounter();
}
}
public class Display{
Foo foo = new Foo();
public void displayCounter(){
foo.incrCounter();
System.out.println(foo.getCounter());
}
}
This should print out "3"
Upvotes: 2
Views: 3976
Reputation: 726509
In C++, scope resolution operator ::
is used instead of .
in Java. You call static methods like this:
In the header:
class MyClass {
public:
static int myPrivateStaticVar;
static void myStaticMethod();
};
In the cpp file:
#include "myfile.h"
#include <iostream>
using namespace std;
int MyClass::myPrivateStaticVar = 123;
void MyClass::myStaticMethod() {
cerr << "hello, world! " << myPrivateStaticVar << endl;
}
int main() {
MyClass::myStaticMethod();
}
Your static method myStaticMethod
needs to be public in the MyClass
class.
Upvotes: 2
Reputation: 234424
In Java, you can access a class in as many other classes as you like and the values in the class you are accessing will always be the same as long as the variables are static.
You mean, like a global variable? You can declare a global variable like this:
extern int foo;
You will need one definition of it, which goes like this:
int foo = 42;
The declaration will work well if put in a header file that is included anywhere it is need, and the definition should go in one source file.
Upvotes: 0