【问题标题】:Declare and Initialize a const Struct in Class Header在类头中声明并初始化一个 const Struct
【发布时间】:2014-10-24 13:31:41
【问题描述】:

我正在寻找在我的类头文件中声明和初始化常量结构的方法。 如您所见,该类正被 MFC 应用程序使用。 我的 MFC Dialog 上的层永远不会改变,所以我想不断地对它们进行 decare。

我正在寻找这样的东西:

class CLayerDialog : CDialogEx
{
...
public:
   const LAYER_AREA(CPoint(0, 70), CPoint(280, 140));
}

结构:

struct LAYER_AREA{
   CPoint topLeft;
   CPoint bottomRight;
};

最好的方法是什么,以尽可能多地节省性能并轻松维护层?

【问题讨论】:

  • 你到底在问什么?
  • 所以您希望 LAYER_AREA 在每个对象中都是 const,或者您希望它是 CLayerDialog 的所有对象中可用的同一个对象?
  • 我希望它是 CLayerDialog 的同一个对象。始终保持不变,是的

标签: c++ struct header constants declare


【解决方案1】:

您的意思是static const 成员变量吗?

// header file
class CLayerDialog : CDialogEx
{
/* ... */
public:
   static const LAYER_AREA myvar;
};

// source file
const LAYER_AREA CLayerDialog::myvar(CPoint(0, 70), CPoint(280, 140));

请注意,变量必须在行外定义(在源文件中而不是在头文件中)。您还需要一个合适的 struct LAYER_AREA 构造函数。

【讨论】:

  • 这在 C++03 中是正确的,并且可能仍然是 Visual C++ 的最佳方法,尽管下一个版本应该对 brace-or-equal-initializer有更好的支持> 语法。
  • 好的,那么我将不得不为此使用 CPP 文件?
  • @Future:是的,CPP“源文件”。
【解决方案2】:

你可以这样做:(我对你没有提供的类做了一些假设)

在头文件中

class CDialogEx
{
   public:
      CDialogEx (){}
};

class CPoint
{
   public:
      CPoint ( const int& _x, const int& _y ):x(_x), y(_y){}

   private:
      int x;
      int y;

};

struct LAYER_AREA
{
   CPoint topLeft;
   CPoint bottomRight;
   LAYER_AREA ( CPoint tl, CPoint br ):
      topLeft ( tl ), bottomRight ( br )
   {
   }
};

class CLayerDialog : CDialogEx
{
   public:
      CLayerDialog ();
      const LAYER_AREA myStructVar;
};

在 .cpp 文件中

CLayerDialog::CLayerDialog()
  : myStructVar ( CPoint(0, 70), CPoint(280, 140) )
{

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-09
    • 2012-02-26
    • 2015-04-05
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多