You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++ GDI+ Image类报错C2248:无法访问私有成员的解决求助

问题分析与可运行代码示例

你的代码存在几个关键问题:

  • 字符串声明错误:wchar_t filename = L'bunny.png';是单个宽字符变量,无法存储完整文件名,应改为const wchar_t*类型指向宽字符串
  • Gdiplus的Image类不能直接通过构造函数实例化,它的多数构造函数为protected/private权限,必须使用静态工厂方法Image::FromFile创建实例
  • Graphics对象不能直接用Image*初始化,需要绑定到窗口的设备上下文(HDC)或窗口句柄(HWND)

以下是完整的可运行代码,包含Gdiplus初始化、图片加载绘制和资源清理流程:

#include <windows.h>
#include <gdiplus.h>
#pragma comment(lib, "gdiplus.lib") // 编译时链接Gdiplus库

using namespace Gdiplus;

// 窗口消息处理函数
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
        case WM_PAINT:
        {
            PAINTSTRUCT ps;
            HDC hdc = BeginPaint(hwnd, &ps);

            // 绑定窗口HDC创建Graphics对象
            Graphics graphics(hdc);

            // 加载PNG图片
            Image* pImage = Image::FromFile(L"bunny.png");
            if (pImage != nullptr)
            {
                // 在窗口(10,60)位置绘制图片
                graphics.DrawImage(pImage, 10, 60);
                delete pImage; // 释放图片资源
            }

            EndPaint(hwnd, &ps);
            return 0;
        }
        case WM_DESTROY:
            PostQuitMessage(0);
            return 0;
        default:
            return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    // 初始化Gdiplus
    GdiplusStartupInput gdiplusInput;
    ULONG_PTR gdiplusToken;
    GdiplusStartup(&gdiplusToken, &gdiplusInput, nullptr);

    // 注册窗口类
    const wchar_t CLASS_NAME[] = L"PNGImageDemo";
    WNDCLASS wc = {0};
    wc.lpfnWndProc = WindowProc;
    wc.hInstance = hInstance;
    wc.lpszClassName = CLASS_NAME;
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wc.hCursor = LoadCursor(nullptr, IDC_ARROW);

    RegisterClass(&wc);

    // 创建窗口
    HWND hwnd = CreateWindowEx(
        0,
        CLASS_NAME,
        L"Gdiplus PNG绘制示例",
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT, 640, 480,
        nullptr, nullptr, hInstance, nullptr
    );

    if (hwnd == nullptr) return 0;

    ShowWindow(hwnd, nCmdShow);

    // 消息循环
    MSG msg;
    while (GetMessage(&msg, nullptr, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    // 清理Gdiplus资源
    GdiplusShutdown(gdiplusToken);
    return (int)msg.wParam;
}

注意:确保bunny.png文件位于程序工作目录下,或使用完整路径(如L"C:\\images\\bunny.png")

内容的提问来源于stack exchange,提问作者Timofey Kalakutsky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 20:05:17