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;
}
运行结果: