如何让继承的ImportTemplate函数无需传入this即可获取调用者指针?
问题:如何让
ImportTemplate无需传入this直接获取调用者的指针? 现有代码结构
基类1:CBaseEditor
class CBaseEditor { public: bool CBaseEditor::ImportTemplate(CWnd* pParent) { CFileDialog dlgImport(TRUE, _T(".XSL"), _T(""), OFN_ALLOWMULTISELECT | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, _T("FilterText"), pParent); } }
基类2:CResizingDialog
class CResizingDialog : public CDialogEx { }
多继承的对话框类
class CFieldServiceGroupReportDlg : public CResizingDialog, public CBaseEditor { private: void SuneFunc() { ImportTemplate(this); } }
我的疑问是:ImportTemplate函数能不能不用每次传入this,直接获取调用者的this指针?
后续思路与现有构造函数代码
根据思路,我认为最佳方案是修改构造函数(对话框类已重命名为CPublishersDatabaseViewerDlg):
CPublishersDatabaseViewerDlg::CPublishersDatabaseViewerDlg(CWnd* pParent /*=nullptr*/) : CResizingDialog(L"GroupsReport", IDD_DIALOG_PUBLISHERS_DATABASE_VIEWER, pParent) , m_strPreviewXSL(L"") { m_strPreviewXSL = theApp.GetStringSetting(L"Options", L"PublisherDB_Style", L"PublisherDB--Field Service Groups"); }
按照现有设计,对话框类会接收父窗口指针。同理,我应该修改CBaseEditor,让它能以某种方式获取合适的父窗口指针,这样就不用每次调用ImportTemplate都传参数了。以下是当前两个基类的构造函数:
CResizingDialog构造函数
CResizingDialog::CResizingDialog(const CString& strWindowID, UINT nIDTemplate, CWnd* pParent /* nullptr */, bool bOnlyStorePosition /* false */) : CDialogEx(nIDTemplate, pParent) , m_bDoNotShowResizeIcon(false) , m_bOnlyStorePosition(bOnlyStorePosition) , m_bLimitToHorizontalResizing(false) , m_strWindowID(strWindowID) { m_rcInit.SetRect(0, 0, 0, 0); }
CBaseEditor构造函数
CBaseEditor::CBaseEditor() noexcept(false) { Init(); }
解决方案
要实现ImportTemplate无需传入this,可以通过给CBaseEditor添加成员变量存储窗口指针,并修改构造函数传递该指针:
- 修改
CBaseEditor类,添加私有成员变量存储窗口指针,更新构造函数并调整ImportTemplate的参数:
class CBaseEditor { private: CWnd* m_pOwnerWnd; // 存储所属窗口指针 public: // 修改构造函数,接收窗口指针 CBaseEditor(CWnd* pOwnerWnd) noexcept(false) : m_pOwnerWnd(pOwnerWnd) { Init(); } bool ImportTemplate() // 不再需要传入pParent参数 { CFileDialog dlgImport(TRUE, _T(".XSL"), _T(""), OFN_ALLOWMULTISELECT | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY, _T("FilterText"), m_pOwnerWnd); // 使用成员变量 // 后续逻辑... } }
- 修改派生类的构造函数,在初始化列表中传递
this给CBaseEditor:
CPublishersDatabaseViewerDlg::CPublishersDatabaseViewerDlg(CWnd* pParent /*=nullptr*/) : CResizingDialog(L"GroupsReport", IDD_DIALOG_PUBLISHERS_DATABASE_VIEWER, pParent) , CBaseEditor(this) // 传递当前对话框指针给CBaseEditor , m_strPreviewXSL(L"") { m_strPreviewXSL = theApp.GetStringSetting(L"Options", L"PublisherDB_Style", L"PublisherDB--Field Service Groups"); }
- 调用
ImportTemplate时无需传参:
void CFieldServiceGroupReportDlg::SuneFunc() { ImportTemplate(); // 直接调用,无需传入this }
这样修改后,CBaseEditor在构造时就持有了派生类窗口的指针,ImportTemplate可以直接使用该成员变量,不用每次调用都手动传递this。
内容的提问来源于stack exchange,提问作者Andrew Truckle
相关产品推荐
相关产品推荐

