类中构造函数能不能为虚函数,我在我的另一个博客中已经做了一些解释,不过在遇到一些其他问题时总是不能做出很好的解释,所以这次我们再将其做一下讨论。
前一篇博客中我已经解释过构造函数不能为虚函数:因为调用虚函数需要虚函数指针,而构造函数此时还没有被调用,还没有虚函数指针所以会出错。
但是构造函数中能不能调用虚函数呢?答案是可以。但是我前面说过构造函数对对象进行初始化,因为构造函数还没有完成,所以仍然没有虚函数指针怎么能调用虚函数呢?
下面我们举一个例子:
初始化落在构造函数的身上,这个很简单但是千万别混淆赋值与初始化
class ABEntry{
public:
ABEntry(const cosnt ::std String &name, const std::string &adress, const std::list<PhoneNumber>&phone);
private:
std:: string theName;
std::string theAddress;
std::list<PhoneNumber> thePhone;
int numTimeConsulted;
;
ABEntry::ABEntry(const cosnt ::std String &name, const std::string &adress, const std::list<PhoneNumber>&ohone)
{
theNmme = name; //这些都是赋值而非初始化
theAddress = address;
thePhone = phone;
numTimesConsult = 0;
}
对象成员变量的初始化发生在进入构造函数本体之前,在ABEntry构造函数内部,theName。。。这些变量都不叫初始化这些叫做赋值,初始化发生更早(比进入ABEntry构造函数体时间更早)。这就解释为什么在构造函数内部可以调用虚函数,因为一旦进入构造函数内部对象就已经初始化完毕,虚函数指针也已经初始化,所以是可以调用的。