C++ 如何调用另一个类的静态方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4365982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:14:27  来源:igfitidea点击:

How do I call a static method of another class

c++windowsoopmfcstatic-methods

提问by Simsons

I have a class, lets say CAppPathwhich has a static method:

我有一个类,让我们说它CAppPath有一个静态方法:

public:
    static CString GetAppPath();

and in CAppPath.cppit's defined as:

并在CAppPath.cpp其中定义为:

CString CAppPath::GetAppPath()
{

    return "C:\..\MypAth";
}

Now I have another class CXMLHandler, and I have included CAppPath.hin it. But how do I call the GetAppPath()method? I've tried:

现在我有另一个类CXMLHandler,我已经包含CAppPath.h在其中。但是我如何调用该GetAppPath()方法?我试过了:

#include "CAppPath.h"
void CXMLHandler::MyMethod
{
CNDSClientDlg->GetAppPath();
}

but it doesn't work. How should I access this method? Since it is a static method, do I need to create a object of the class or should I make the class itself static?

但它不起作用。我应该如何访问这个方法?由于它是一个静态方法,我是否需要创建类的对象还是应该使类本身成为静态的?

回答by Frédéric Hamidi

You only need to use the scope resolution operator::to qualify the method with the name of the class that exposes it:

您只需要使用范围解析运算符::来限定具有公开它的类的名称的方法:

CString appPath = CAppPath::GetAppPath();