【问题标题】:How do I call a static method of another class如何调用另一个类的静态方法
【发布时间】:2011-05-20 22:35:16
【问题描述】:

我有一个类,比如说CAppPath,它有一个静态方法:

public:
    static CString GetAppPath();

CAppPath.cpp 中定义为:

CString CAppPath::GetAppPath()
{

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

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

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

但它不起作用。我应该如何访问此方法?既然是静态方法,那我需要创建类的对象还是让类本身静态?

【问题讨论】:

    标签: c++ windows oop mfc static-methods


    【解决方案1】:

    您只需要使用scope resolution operator :: 来使用公开它的类的名称来限定方法:

    CString appPath = CAppPath::GetAppPath();
    

    【讨论】:

    • 谢谢,在这种情况下我需要静态方法吗?
    • @Subhen,是的,你知道。如果方法不是静态的,则必须创建 CAppPath 类的新实例才能在该实例上调用 GetAppPath() 方法。
    猜你喜欢
    • 2015-02-13
    • 2013-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多