发表于2008-04-04 15时31分 更新于2008-04-04 15时31分 构造函数并不存在继承,因为在c++中,构造函数是自动调用的,子类会调用父类的构造函数。而且构造的顺序如下,
(0)首先调用父类成员的构造函数;
(1)首先调用父类构造函数;
(2)调用子类成员对象的构造函数;
(3)子类自己的构造函数。
析构顺序与上面严格相反!
因此,因为是先调用父类构造函数,在父类的构造函数中,其虚函数表并未完全形成,要想在父类构造函数中使用多态功能是错误的!
譬如下代码:想在父类构造函数中实现多态,结果输出的却是父类的virfun。
class father
{
public:
father()
{
cout<<"father::father()/n";
virfun();
}
virtual virfun()
{
cout << "father virtual fun()/n";
}
};
class son : public father
{
public:
son()
{
cout<<"son::son()/n";
}
virtual virfun()
{
cout << "son virtual fun()/n";
}
};
int main()
{
son* p = new son();
return 0;
}
{
public:
father()
{
cout<<"father::father()/n";
virfun();
}
virtual virfun()
{
cout << "father virtual fun()/n";
}
};
class son : public father
{
public:
son()
{
cout<<"son::son()/n";
}
virtual virfun()
{
cout << "son virtual fun()/n";
}
};
int main()
{
son* p = new son();
return 0;
}
其原因,可以从this的变化过程中看出,如下图所示
而采用下述代码,则能正确地实现多态
class father
{
public:
virtual virfun()
{
cout << "father virtual fun()/n";
}
testfun()
{
virfun();
}
};
class son : public father
{
public:
virtual virfun()
{
cout << "son virtual fun()/n";
}
};
int main()
{
father* p = new son();
p->testfun();
return 0;
}
{
public:
virtual virfun()
{
cout << "father virtual fun()/n";
}
testfun()
{
virfun();
}
};
class son : public father
{
public:
virtual virfun()
{
cout << "son virtual fun()/n";
}
};
int main()
{
father* p = new son();
p->testfun();
return 0;
}