C++中构造函数与析构函数能否为虚函数
看书时发现,C++中的基类的构造函数不能为虚函数(VC6.0中为虚函数是不能通过编译的),析构函数应该为虚函数(MFC中CObject的析构函数即为虚函数)。
通过以下面的代码,来看看这样的说法对不对:
测试一:
Java代码
#include <iostream>
using namespace std;
class Base
{
public:
Base()
{
cout << "Base::Base()" <<endl;
}
~Base()
{
cout << "Base::~Base()" <<endl;
}
};
class Derived : public Base
{
public:
Derived()
{
cout << "Derived::Derived()" <<endl;
}
~Derived()
{
cout << "Derived::~Derived()" <<endl;
}
};
int main(int argc, char* argv[])
{
Derived d; // 依次调用Base::Base(),Derived::Derived()
// 程序结束时依次调用Derived::~Derived(),Base::~Base()
return 0; // 注意现在基类的析构函数不是虚函数,但是按照调用顺序不会造成内存泄露。
}
测试二:
Java代码
#include <iostream>
using namespace std;
class Base
{
public:
Base()
{
cout << "Base::Base()" <<endl;
}
~Base()
{
cout << "Base::~Base()" <<endl;
}
};
class Derived : public Base
{
public:
Derived()
{
cout << "Derived::Derived()" <<endl;
}
~Derived()
{
cout << "Derived::~Derived()" <<endl;
}
};
int main(int argc, char* argv[])
{
Derived *d2 = new Derived(); // 依次调用Base::Base(),Derived::Derived()
Base *pBase = d2;
delete pBase; // 只调用了Base::~Base(),而没有调用Derived::~Derived()
// 因为这里基类的析构函数不是虚函数
return 0;
}
测试三:
Java代码
#include <iostream>
using namespace std;
class Base
{
public:
Base()
{
cout << "Base::Base()" <<endl;
}
virtual ~Base()
{
cout << "Base::~Base()" <<endl;
}
};
class Derived : public Base
{
public:
Derived()
{
cout << "Derived::Derived()" <<endl;
}
~Derived()
{
cout << "Derived::~Derived()" <<endl;
}
};
int main(int argc, char* argv[])
{
Derived *d2 = new Derived(); // 依次调用Base::Base(),Derived::Derived()
Base *pBase = d2;
delete pBase; // 依次调用Derived::~Derived(),Base::~Base(),
// 因为这里基类的析构函数是虚函数
return 0;
}
总结:
(1) 假如你不打算使用多态(用基类指针指向派生类实例),基类析构函数是否为虚函数是无关紧要的。
(2) 假如你打算使用多态,一定要注意了,让基类的析构函数为虚函数。
PS: 对于非虚函数的调用,完全取决于指针的类型。因为非虚函数的地址在编译阶段就会根据指针的类型确定下来。举一个简单的例子,派生类有一个非虚函数f(),基类中不存在这样的函数。使用一个基类指针指向一个派生类实例后,假如你打算使用这个基类指针调用f(),编译器会让你打消这个念头(编译无法通过)。
作者“icebergs”
补充:软件开发 , C++ ,