不是所有的函数都能自动地从基类继承到派生类中的。构造函数和析构函数是用来处理对象的创建和析构的,它们只知道对在它们的特殊层次的对象做什么。所以,在整个层次中的所有的构造函数和析构函数都必须被调用,也就是说,构造函数和析构函数不能被继承。
另外,operator= 也不能被继承,因为它完成类似于构造函数的活动。
//: NINHERIT.CPP -- Non-inherited functions #include <fstream.h> class root { public: root() { cout << "root() "; } root(root&) { cout << "root(root&) "; } root(int) { cout << "root(int) "; } root& operator=(const root&) { cout << "root::operator=() "; return *this; } class other {}; // 定义内部类 operator other() const { cout << "root::operator other() "; return other(); } ~root() { cout << "~root() "; } }; class derived : public root {}; void f(root::other) {} // 使用内部类,这样定义不多见 main() { derived d1; // Default constructor derived d2 = d1; // Copy-constructor //! derived d3(1); // Error: no int constructor d1 = d2; // Operator= not inherited f(d1); // Type-conversion IS inherited }
输出结果:
root()
root(root&)
root::operator=()
root::operator other()
~root()
~root()