本文用来测试C++基类和派生类构造函数,析构函数,和拷贝构造函数的调用次序。
运行环境:SUSE Linux Enterprise Server 11 SP2 (x86_64)
#include
using namespace std;
class Base
{
public:
Base()
{
cout << "Base Constructor" << std::endl;
}
Base(const Base& other)
{
cout << "Base Copy Constructor" << std::endl;
}
virtual ~Base()
{
cout << "Base Destructor" << std::endl;
}
const Base & operator = (const Base& other)
{
cout << "assignment operator" << std::endl;
}
};
class Derived: public Base
{
public:
Derived()
{
cout << "Derived Constructor" << std::endl;
}
Derived(const Derived& other)
{
cout << "Derived Copy Constructor" << std::endl;
}
virtual ~Derived()
{
cout << "Derived Destructor" << std::endl;
}
const Derived & operator = (const Derived& other)
{
cout << "assignment operator" << std::endl;
}
};
==============================================================
A. 测试派生类对象
int main(int argc, char *argv[])
{
Derived d1;
return 1;
}
输出:
Base Constructor
Derived Constructor
Derived Destructor
Base Destructor
结论:
1.先构造父类,才构造子类,没有父亲,哪有儿子啊!
2.即使子类(派生类)没有显式(explicit)的调用(在初始化列表中调用)父类(基类)的构造函数,父类的构造函数也会被调用;
================================================================
B. 测试基类的拷贝构造函数
int main(int argc, char *argv[])
{
Base b1;
cout << "b1 constructed done" << std::endl;
Base b2 = b1;
cout << "b2 constructed done" << std::endl;
Base b3(b2);
cout << "b3 constructed done" << std::endl;
return 1;
}
输出结果:
Base Constructor
b1 constructed done
Base Copy Constructor
b2 constructed done
Base Copy Constructor
b3 constructed done
Base Destructor
Base Destructor
Base Destructor
结论:
1. 代码: "Base b2 = b1;" 和 "Base b3(b2);"
将调用拷贝构造函数,而不是其它的(赋值、构造)函数;
扩展: 函数参数传值调用也会调用拷贝构造函数
添加函数:
void Func(Base b)
{
}
int main(int argc, char *argv[])
{
Base b1;
cout << "b1 constructed done" << std::endl;
Func(b1);
return 1;
}
输出结果:
Base Constructor
b1 constructed done
Base Copy Constructor
Base Destructor
Base Destructor
可见: 函数参数传值调用也会调用拷贝构造函数
==================================================================
C. 测试派生类的拷贝构造函数
int main(int argc, char *argv[])
{
Derived b1;
cout << "b1 constructed done" << std::endl;
Derived b2 = b1;
cout << "b2 constructed done" << std::endl;
Derived b3(b2);
cout << "b3 constructed done" << std::endl;
return 1;
}
输出结果:
Base Constructor
Derived Constructor
b1 constructed done
Base Constructor
Derived Copy Constructor
b2 constructed done
Base Constructor
Derived Copy Constructor
b3 constructed done
Derived Destructor
Base Destructor
Derived Destructor
Base Destructor
Derived Destructor
Base Destructor
结论:
1. 派生类的拷贝构造函数被调用前,会调用子类的构造函数;