c++ - 是否可以删除特定文件的声明和宏?

标签 c++

我有一个头文件(我们称之为 Window.h),有点像这样:

#include <windows.h>

class Window {
    Window();
    HWND hwnd;
}

要在另一个文件(例如 Main.cpp)中使用此类,必须包含 Window.h:

#include "Window.h"

问题是我不希望 Main.cpp 包含 windows.h,因为 windows.h 在我不希望出现在 Main.cpp 中的命名空间之外添加了许多宏和新声明。我无法将 windows.h 移动到 Window.h 的实现(Window.cpp),因为该类具有 HWND 属性。

我能想到的唯一解决方法是将 hwnd 声明为指针:

void* hwnd;

但我不喜欢这种方法。如果你经常这样做,事情可能会变得非常困惑。有没有更好的方法来做到这一点,也许以某种方式从 Main.cpp 文件中“删除”声明和宏?

最佳答案

不,您无法“删除”声明,但可以通过两种方式隐藏它: 1.Impl-Pimpl惯用法

//.h file
class Window {
   class Impl;
   Impl* pImpl;
   Window();
   ~Window();
   void doSomething();
};


//.cpp file
#include <windows.h>

struct Window::Impl
{
   HWND hwnd;
};

Window::Window()
{
   pImpl = new Window::Impl;
}

Window::~Window()
{
   delete pImpl;
}

void Window::doSomething()
{
   //foo(pImpl->hwnd);
}

2.抽象类。

//.h file
class Window
{
public:
   static Window* newWindow();
   virtual void doSomething() = 0;
   virtual ~Window() {};
};

//.cpp file
#include <windows.h>

class WindowImpl : public Window
{
   HWND hwnd;
   void Window::doSomething() override
   {
      //foo(pImpl->hwnd);
   }
};


Window* Window::newWindow()
{
   return new WindowImpl();
}

关于c++ - 是否可以删除特定文件的声明和宏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53658595/

相关文章:

c++ - 如何在 C++ 中将枚举的十六进制值打印到字符串

c++ - 具有复杂条目的 ODE

c++ - 在 Visual Studio 2008 中使用 C++ 创建简单 COM 组件的示例

c++ - 如何将char转换为wchar_t *?

c++ - CopyMemory 复制比 VirtualAlloc 分配更多的字节怎么办

c++ - 断点未命中静态链接库中的全局静态初始化类

c++ - 如何在 C++ 中使用 MATLAB 函数 randn?

c++ - 结构的 cudaMalloc 和相同结构的元素

c++ - 为什么 UuidFromString 函数请求非常量指针指向 unsigned char?

c++ - 如何覆盖运算符 <