如何访问父类mfc上的变量

Posted

技术标签:

【中文标题】如何访问父类mfc上的变量【英文标题】:How to access to variable on parent class mfc 【发布时间】:2015-07-07 07:46:08 【问题描述】:

我有一个关于 MFC 应用程序的对话框。

MyDialog :

 int variable1;
 int variable2;
 Class1 cls = new Class1();

在 class1() 中

 Class1() 
 
     void Function1()
     void Function2()
 

--

那么如何在Class1::Function1()中访问并返回variable1

Class1::Function1()

  MyDialog dlg = new MyDialog ();
  Get x = dlg->variable1; //if like this, variable1 alway=0, because in above line, i'm define new myDialog()

我想在 .NET 上委托,但在 MFC 应用程序中,我无法完成?

【问题讨论】:

一个好的做法是重写你的问题,更清楚...... 【参考方案1】:

你可以

    “扩展”您的构造函数,方法是在子对话框中添加指向父级的指针并访问您的变量或调用公共函数(需要父级的标头) 使用SendMessage 并处理父对话框中的消息 在您的父对话框中使用GetParentdynamic_cast(需要父对话框的标题)

1.

Class1::Class1(MyParent *parent)

    m_parentPointer = parent;

void Class1::Function1(void)

    m_parentPointer->myPublicVariable;

2.

void Class1::Function1(void)

    CWnd *parent = GetParent();
    if (parent)
        parent->SendMessage(WM_YOUR_MESSAGE, yourWPARAM, yourLPARAM);


//MessageMap of parent
ON_MESSAGE(WM_YOUR_MESSAGE, ParentClassHandler)

LRESULT Parent::ParentClassHandler(WPARAM wp, LPARAM lp)

    //Process

3.

void Class1::Function1(void)

    CWnd *parent = GetParent();
    if (parent)
    
        Parent *p = dynamic_cast<Parent*>(parent);
        if (p)
        
            //Process
        
    

【讨论】:

【参考方案2】:

如果Class1::Function1() 需要访问对话框,那么您需要一个指向Function1 中对话框的指针。

void Class1::Function1(MyDialog *dlg) 

如果要永久保存对话框指针,则调整Class1的构造函数。

class Class1 
public:
    Class1(class MyDialog *dlg_) : dlg(dlg_) 
    class MyDialog *dlg;

实现它的另一种可能更好的方法是将需要访问 Class1 和 MyDialog 的代码移动到全局函数或 MyDialog 成员函数中。但走哪条路取决于类做什么以及您想要哪种设计。

【讨论】:

感谢您的回答。我会试试这个方法!我想在 MyDialog void Class1::Function1(MyDialog *dlg) dlg->function() 中调用一个函数【参考方案3】:

在深入研究之前,您必须从基本的 C++ 类开始。但它是这样完成的:

MyDialog dlg = new MyDialog ();

dlg->variable1 = 1; //set the variable

if (IDOK == dlg->DoModal()) //wait for user to click OK

    int x = dlg->variable1; //get the variable

但是,dlg-&gt;variable1 不会更改,除非您驾驶自己的班级并做一些事情来改变它。

例如,您可以使用Dialog Data Exchange 将variable1 分配给复选框。

void MyDialog::DoDataExchange(CDataExchange* pDX)

    CDialog::DoDataExchange(pDX);
    DDX_Check(pDX, IDC_CHECK1, variable1);

要试用它,请使用 Visual Studio 的对话框向导创建一个复选框和一个编辑框。它可能会创建一个资源 id 为IDC_CHECK1 的复选框,一个资源id 设置为IDC_EDIT1 的编辑框。

另一种选择:

使用OnInitDialog 将变量分配给对话框控件

使用OnOK() 从对话框控件中获取变量:

BOOL MyDialog::OnInitDialog()

    //put `CString m_string1;` in class declaration
    BOOL result = CDialog::OnInitDialog();
    SetDlgItemText(IDC_EDIT1, m_string1);
    return result;


void MyDialog::OnOK()

    GetDlgItemText(IDC_EDIT1, m_string1);
    CDialog::OnOK();

【讨论】:

以上是关于如何访问父类mfc上的变量的主要内容,如果未能解决你的问题,请参考以下文章

子类如何访问父类

如何使用 MFC 在项目的所有对话框中访问变量?

(MFC) 如果控件是私有成员,父类如何接收控件的消息?

如何从 C++ 中的子类访问父类的成员变量?

as3.0父类 parent中我要用到子类subclass中的一个名为key的变量,如何访问

mfc怎么设置全局变量