您的位置:首页 > 其它

构造与析构函数以及=操作符不能被继承,以及内部类的用法

2014-04-27 22:27 309 查看
不是所有的函数都能自动地从基类继承到派生类中的。构造函数和析构函数是用来处理对象的创建和析构的,它们只知道对在它们的特殊层次的对象做什么。所以,在整个层次中的所有的构造函数和析构函数都必须被调用,也就是说,构造函数和析构函数不能被继承。
另外,operator= 也不能被继承,因为它完成类似于构造函数的活动。

//: NINHERIT.CPP -- Non-inherited functions
#include <fstream.h>

class root {
public:
root() { cout << "root()\n"; }
root(root&) { cout << "root(root&)\n"; }
root(int) { cout << "root(int)\n"; }
root& operator=(const root&) {
cout << "root::operator=()\n";
return *this;
}

class other {}; // 定义内部类
operator other() const {
cout << "root::operator other()\n";
return other();
}
~root() { cout << "~root()\n"; }
};

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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐