在MFC的程序中,我们经常会看到下面的程序片段,
片段一:
BOOL CClassDlg::OnInitDialog()
{
CDialog::OnInitDialog();
//。。。。
//。。。。
AddTree();
returnTRUE; // return TRUE unless you set thefocus to a control
// EXCEPTION: OCX Property Pagesshould return FALSE
}
片段二:void CMyPosDlg::OnClose()
{
if(AfxMessageBox("确定要退出吗?",MB_YESNO)==IDYES)
CDialog::OnClose();
}
片段三:
int CMyPosApp::ExitInstance()
{
//TODO: Add your specialized code here and/or call the base class
if(m_pConnection->State)
m_pConnection->Close();///如果已经打开了连接则关闭它
return CWinApp::ExitInstance();
}
其实,
派生类成员函数可以调用基类成员函数,
在派生类的普通成员函数中,使用基类作用域调用基类的静态成员函数和普通成员函数都可以
下面用一个具体的实例来验证这一点:
#include "iostream"
using namespace std;
class A
{
public:
int m;
int n;
public:
void function1()
{
cout<<"这是基类的普通函数function1\n";
}
void virtual function2()
{
cout<<"这是基类的虚函数function2\n";
}
static void function3()
{
cout<<"这是基类静态成员函数function3\n";
}
};
class B:public A
{
public:
void function1()
{
A::function1();
}
void function2()
{
cout<<"这是派生类的函数function2\n";
A::function2();
}
};
int main()
{
B b;
b.function1(); // (1)
b.function2(); // (2)
A::function3();// (3)
A *a;
a=new B;
a->function1(); // (4)
a->function2(); // (5)
a->function3(); // (6)
return 0;
}
分析:
(1) (2)其实就是测试派生类函数调用基类的函数,
在B类中,function1直接调用A类的function1,
function2 相当于重写了A类的function2函数,因为加入了新的语句
(3)是测试用类名直接调用类中的静态成员函数
(4)(5)(6)其实是在测试多态,只有function2函数才会调用子类的函数,其他的都只调用基类的函数,因为function2是虚函数,这也是虚函数在多态中的作用(动态联编)
另外,由于B是A类的派生类,function3是A类的静态函数,
所以,也可以直接用B::function3(); 来调用function3