菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
338
0

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

原创
05/13 14:22
阅读数 946294

标签:com   http   class   blog   style   img   div   code   java   javascript   color   

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

bubuko.com,布布扣
//: 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
}
bubuko.com,布布扣

输出结果:

root()
root(root&)
root::operator=()
root::operator other()
~root()
~root()

构造与析构函数与=不能被继承,以及内部类的用法,布布扣,bubuko.com

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

发表评论

0/200
338 点赞
0 评论
收藏
为你推荐 换一批