我是整个编程的新手。即使我认为我已经掌握了课程和包括的基本概念,但我无法弄清楚我在这里做错了什么。我创建了自己的名为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对象,每个函数都可以访问。
亲切的问候, Michen
答案 0 :(得分:1)
Grid theGrid{ GetSafeHwnd() };
在构造函数内声明,因此仅获得局部作用域。您必须在构造函数之外声明它并在构造函数上初始化它,如:
--.h file--
public class CMainFrame{
Grid theGrid;
[...]
--.cpp file---
CMainFrame::CMainFrame() :
theGrid(GetSafeHwnd())
{}
答案 1 :(得分:0)
在MainFrm.cpp开头#include“Grid.h”
答案 2 :(得分:0)
在您的CMainFrame.h文件中包含Grid.h并将theGrid定义为CMainFrame中的成员变量
在MainFrm.h中
#include "Grid.h"
...
class CMainFrame
{
....
Grid theGrid;
...
};
我是MainFrm.cpp
#inlcude "MainFrm.h"
...
CMainFrame::CMainFrame() : theGrid(GetSafeHwnd())
{
// TODO: add member initialization code here
}