我是一名学习MFC的学生。
我想声明 ChildView 区域变量。
我必须在哪里声明变量?头文件?还是cpp文件?
我认为两者都很好。但我想知道一般风格。
请告诉我哪些是可取的。
// ChildView.h : interface of the CChildView class
//
#pragma once
// CChildView window
class CChildView : public CWnd
{
// Construction
public:
CChildView();
...
...
// User variables
public:
CFile* pImgFile = NULL;
ULONGLONG imgLength, frameLength;
unsigned char RRR[288][352];
unsigned char GGG[288][352];
unsigned char BBB[288][352];
unsigned char YYY[288][352];
unsigned char UUU[144][176];
unsigned char VVV[144][176];
};
或
// ChildView.cpp : implementation of the CChildView class
//
#include "stdafx.h"
#include "Doyup_YUV_HW7-8.h"
#include "ChildView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CChildView
CChildView::CChildView()
{
CFile* pImgFile = NULL;
ULONGLONG imgLength, frameLength;
unsigned char RRR[288][352];
unsigned char GGG[288][352];
unsigned char BBB[288][352];
unsigned char YYY[288][352];
unsigned char UUU[144][176];
unsigned char VVV[144][176];
}
另外,我也想知道define语句在哪里。
在头文件中 (3)#pragma once 之后?
或在 cpp 文件中的 (9)#endif 之后?
最佳答案
您应该更喜欢第二种方式 - 在 .cpp 文件中声明变量
CChildView::CChildView()
仅在您仅在构造函数中需要变量而在其他函数中不需要它们的情况下。
但我认为您在其他函数中也需要这些变量。在这种情况下,您应该在 .h 文件中声明它们。现在请注意它们,您将它们声明为公共(public)变量,这是个坏主意。您最好将它们声明为私有(private)变量(阅读有关私有(private)和公共(public)变量以及封装的信息)。默认情况下,最好将所有变量声明为私有(private)。
至于定义,最好将它们添加到.cpp 文件中,然后它们将只在您的cpp 文件中可见。如果你在 h 文件中定义了一些东西,当你包含你的 h 文件时,它会在任何地方被定义并且可能会导致冲突。
关于c++ - 根据程序员的哲学,我想知道在哪里声明变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29932952/