a.第一段代码:
#include<iostream>
using namespace std;
class ClxBase{
public:
ClxBase() {cout << "Output from the constructor of class ClxBase!" << endl;};
~ClxBase() {cout << "Output from the destructor of class ClxBase!" << endl;};
void DoSomething() { cout << "Do something in class ClxBase!" << endl; };
};
class ClxDerived : public ClxBase{
public:
ClxDerived() {cout << "Output from the constructor of class ClxDerived!" << endl;};
~ClxDerived() { cout << "Output from the destructor of class ClxDerived!" << endl; };
void DoSomething() { cout << "Do something in class ClxDerived!" << endl; };
};
int main()
{
ClxDerived *p = new ClxDerived;
p->DoSomething();
delete p;
return 0;
}
输出结果:
b.第二段代码:
#include<iostream>
using namespace std;
class ClxBase{
public:
ClxBase() {cout << "Output from the constructor of class ClxBase!" << endl;};
~ClxBase() {cout << "Output from the destructor of class ClxBase!" << endl;};
void DoSomething() { cout << "Do something in class ClxBase!" << endl; };
};
class ClxDerived : public ClxBase{
public:
ClxDerived() {cout << "Output from the constructor of class ClxDerived!" << endl;};
~ClxDerived() { cout << "Output from the destructor of class ClxDerived!" << endl; };
void DoSomething() { cout << "Do something in class ClxDerived!" << endl; };
};
int main()
{
<pre name="code" class="cpp" style="color: rgb(94, 94, 94); line-height: 21.666667938232422px; text-align: justify;"> ClxBase *p = new ClxDerived;p->DoSomething();delete p;return 0;}
运行结果:
C.第三段代码:
#include<iostream>
using namespace std;
class ClxBase{
public:
ClxBase() {cout << "Output from the constructor of class ClxBase!" << endl;};
virtual ~ClxBase() {cout << "Output from the destructor of class ClxBase!" << endl;};
virtual void DoSomething() { cout << "Do something in class ClxBase!" << endl; };
};
class ClxDerived : public ClxBase{
public:
ClxDerived() {cout << "Output from the constructor of class ClxDerived!" << endl;};
~ClxDerived() { cout << "Output from the destructor of class ClxDerived!" << endl; };
void DoSomething() { cout << "Do something in class ClxDerived!" << endl; };
};
int main()
{
ClxDerived *p = new ClxDerived;
p->DoSomething();
delete p;
return 0;
}输出结果:
d.第四段代码:
#include<iostream>
using namespace std;
class ClxBase{
public:
ClxBase() {cout << "Output from the constructor of class ClxBase!" << endl;};
virtual ~ClxBase() {cout << "Output from the destructor of class ClxBase!" << endl;};
virtual void DoSomething() { cout << "Do something in class ClxBase!" << endl; };
};
class ClxDerived : public ClxBase{
public:
ClxDerived() {cout << "Output from the constructor of class ClxDerived!" << endl;};
~ClxDerived() { cout << "Output from the destructor of class ClxDerived!" << endl; };
void DoSomething() { cout << "Do something in class ClxDerived!" << endl; };
};
int main()
{
ClxBase *p = new ClxDerived;
p->DoSomething();
delete p;
return 0;
}
运行结果:
本文通过四个C++代码示例,展示了基类指针指向派生类对象时构造函数与析构函数的调用顺序,以及虚函数机制如何确保正确的函数调用。
903

被折叠的 条评论
为什么被折叠?



