C ++静态方法(在不同的类)(像Java的) [英] C++ Static Methods (In different Classes) (Like Java's)

查看:184
本文介绍了C ++静态方法(在不同的类)(像Java的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有多个.cpp文件时,如何使用类似静态方法的静态方法?

How would I go about making static methods that are used like the static methods in java when I have multiple .cpp files?

在Java中,你可以引用另一个类通过使用MyClass name = new MyClass();并且在任何其他文件中调用此类中的每个变量都是一样的。

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.

我似乎很痛苦,必须能够通过引用传递MyClass&

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.

有没有办法在.cpp文件的顶部定义MyClass名称,而不是创建一个全新的实例的对象在内存中,并擦除所有的进度,例如,如果你想做一个简单的计数器,主类将告诉计数类增加,可见性类将获得计数从计数类并将其打印到屏幕。现在这很简单,你可以传递计数类的可见性,但如果你有20多个方法,那么将很难跟踪。

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.

提前感谢

示例Java代码:

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());
}
}

这应该打印出3

推荐答案

在C ++中,使用范围解析操作符 :: 代替。您调用如下的静态方法:

In C++, scope resolution operator :: is used instead of . in Java. You call static methods like this:

在标题中:

class MyClass {
public:
    static int myPrivateStaticVar;
    static void myStaticMethod();
};

在cpp文件中:

#include "myfile.h"
#include <iostream>

using namespace std;

int MyClass::myPrivateStaticVar = 123;

void MyClass::myStaticMethod() {
    cerr << "hello, world! " << myPrivateStaticVar  << endl;
}

int main() {
    MyClass::myStaticMethod();
}

您的静态方法 myStaticMethod 需要在 MyClass 类中公开。

Your static method myStaticMethod needs to be public in the MyClass class.

这篇关于C ++静态方法(在不同的类)(像Java的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆