类不可访问,尽管包含

Class not accesible in spite of include

本文关键字:包含 访问      更新时间:2023-10-16

我对整个编程过程很陌生。尽管我认为我已经掌握了类和包括的基本概念,但我无法弄清楚我在这里做错了什么。我创建了自己的类,名为Grid,如下所示:

--- Grid.h ---
class Grid{
public:
Grid(HWND wnd);
public:
void paint(CDC &dc, int sqr, bool axis);            //paint the grid
void tag(CDC &dc);
private:
    int square;                                     //square size
    CRect frame;                                    //client area size
};

--- Grid.cpp ---
#include "stdafx.h"
#include "Grid.h"

Grid::Grid(HWND wnd)
    {
    CRect rect;
    GetClientRect(wnd, &rect);                  // get client area size
    frame.left = rect.right / 2 - 387;          // fit frame to margin
    frame.right = frame.left + 774;
    frame.top = rect.bottom - 874;
    frame.bottom = rect.bottom - 100;
}
void Grid::paint(CDC &dc, int sqr, bool axis){
square = sqr;                               // paint grid
CPen penWhite;
penWhite.CreatePen(PS_SOLID, 1, RGB(255, 255, 255));
dc.SelectObject(&penWhite);
dc.Rectangle(frame);
dc.MoveTo(frame.left + square, frame.top);
for (int i = 1; i < 18; i++){
    dc.LineTo(frame.left + square * i, frame.bottom);
    dc.MoveTo(frame.left + square + square * i, frame.top);
}
dc.MoveTo(frame.left, frame.top + square);
for (int i = 1; i < 18; i++){
    dc.LineTo(frame.right, frame.top + square * i);
    dc.MoveTo(frame.left, frame.top + square + square * i);
}
[...]

现在,我正在尝试做的是从另一个类添加此类的对象。正如你可能已经猜到的那样,它是一个 MFC 应用,应该利用我在 Grid 中提供的功能。因此我添加了

--- MainFrm.cpp ---
[...]
// CMainFrame construction/destruction

CMainFrame::CMainFrame()
{
    // TODO: add member initialization code here
    Grid theGrid{ GetSafeHwnd() };
}
CMainFrame::~CMainFrame()
{
}
[...]

我后来称之为:

void CMainFrame::OnPaint()
{
CPaintDC dc(this);   // get device context for paint
// get current window size
CRect rect;
GetClientRect(&rect); // get current client area size
// fill background black
CBrush brushBlack;
brushBlack.CreateSolidBrush(RGB(0, 0, 0));
dc.SelectObject(&brushBlack);
dc.FillRect(rect, &brushBlack);
// paint grid
theGrid.paint(dc, 43, 1);
ReleaseDC(&dc);
}  // end OnPaint()

。但是编译器给了我错误 C2065:"theGrid":未声明的标识符而Intellisense在theGrid.paint(dc,43,1)上咆哮;

我在这里做错了什么?我只想要一个从 MainFrm 中创建的 Grid 对象,每个函数都可以访问该对象。

亲切问候米琛

Grid theGrid{ GetSafeHwnd() };

在构造函数内部声明,因此仅获得本地范围。必须在构造函数外部声明它,并在构造函数上初始化它,如下所示:

--.h file--
public class CMainFrame{
    Grid theGrid;
    [...]
--.cpp file---
CMainFrame::CMainFrame() :
    theGrid(GetSafeHwnd())
{}

MainFrm 的开头 #include"Grid.h.cpp

在 CMainFrame.h 文件中包含 Grid.h,并将 theGrid 定义为 CMainFrame 中的成员变量

在主Frm.h

#include "Grid.h"
...
class CMainFrame
{
....
    Grid theGrid;
...
};

我主要.cpp

#inlcude "MainFrm.h"
...
CMainFrame::CMainFrame() : theGrid(GetSafeHwnd())
{
    // TODO: add member initialization code here
}