gpt4 book ai didi

C++ 在静态函数中使用非静态变量返回类实例

转载 作者:行者123 更新时间:2023-11-28 01:48:05 26 4
gpt4 key购买 nike

我有一个可以打开多个窗口的应用程序。有id与这些窗口相关联。

我有一个 map<uint, Window*>跟踪 ID 和窗口之间映射的数据结构。

我试图返回一个我知道 id 的类的实例:

Window * Window::getWindow(uint id) {

map<uint, Window*>::iterator it = m_windows.find(id);
if (it != m_windows.end())
{
return it->second;
}
}

它被另一个类调用,通过:

Window::getWindow(id)

我发现函数需要声明static为了能够在没有对象本身的情况下调用这个函数,所以函数声明为:

static Window * getWindow(uint id);

问题是 m_windows不是静态的。它声明:

std::map<uint, Window*> m_windows;

因此,我不能(有意地)在此函数中使用它。

我想弄清楚我将如何做到这一点

  • 使用 m_windows从这个静态函数内部

  • 使这个函数成为非静态函数并以不同的方式返回类实例

m_windows也不能是静态的,因为新窗口需要能够添加到此 map 以及从中删除。

谢谢

最佳答案

我的建议:

  1. Window::getWindow 保留为 static 成员函数。

  2. 将 map m_windows 作为实现细节移至实现文件。无需将其保留为类的成员变量,static 或其他。


在 .cpp 文件中,使用:

// Function to return a reference to the map of windows, which
// is stored in a static variable in the function.
static std::map<uint, Window*>& getWindowsMap()
{
static std::map<uint, Window*> windows;
return windows;
}

向 map 添加项目时,使用:

getWindowsMap()[id] = window;

从 map 取回项目时,使用:

Window* window = getWindowsMap()[id];

关于C++ 在静态函数中使用非静态变量返回类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44058538/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com