構造函數中調用虛函數:
[cpp] view plaincopyprint?
#include<iostream>
using namespace std;
class Base
{
public:
Base()
{
print();
}
virtual void print()
{
cout<<"Base::Base()\n";
}
};
class Derived :public Base
{
public:
virtual void print()
{
cout<<"Derived::Derived()\n";
}
};
int main()
{
Base B;
Derived D;
}
#include<iostream>
using namespace std;
class Base
{
public:
Base()
{
print();
}
virtual void print()
{
cout<<"Base::Base()\n";
}
};
class Derived :public Base
{
public:
virtual void print()
{
cout<<"Derived::Derived()\n";
}
};
int main()
{
Base B;
Derived D;
}
運行結果為:
Base::Base();
Base::Base();
對象的基類部分要早於其數據成員,當Derived中的Base部分被構造時,Derived中的其他成員還未被構造,此時調用Derived中的虛函數毫無意義。因為它可能試圖去訪問Derived中那些還未被初始化的數據成員。
析構函數中使用虛函數:
[cpp] view plaincopyprint?
#include<iostream>
using namespace std;
class Base
{
public:
virtual void print()
{
cout<<"Base::Base()\n";
}
~Base()
{
print();
}
};
class Derived :public Base
{
public:
virtual void print()
{
cout<<"Derived::Derived()\n";
}
};
int main()
{
Base B;
Derived D;
}
#include<iostream>
using namespace std;
class Base
{
public:
virtual void print()
{
cout<<"Base::Base()\n";
}
~Base()
{
print();
}
};
class Derived :public Base
{
public:
virtual void print()
{
cout<<"Derived::Derived()\n";
}
};
int main()
{
Base B;
Derived D;
}
運行的結構為:
Base::Base()
Base::Base()
在析構函數中,我們調用的總是Base::Print(),即使當摧毀的是Derived中的Base部分時也是如此,當我們調用Base的析構函數時,Derived中的數據成員早已被析構了,因此再去調用Derived中的print也將毫無意義。
Attention:只有在構造函數和析構函數中調用虛函數才會有這種特殊的行為出現,其他情況下都是正常的。