我是整个编程领域的新手。即使我以为我已经掌握了类及其包含的基本概念,但我无法弄清楚我在这里做错了什么。我制作了自己的名为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())
{}
关于c++ - 尽管包含但无法访问该类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35942176/