第13周 程序阅读-虚析构函数

#include <iostream>
using namespace std;
class BASE
{
private:
    char c;
public:
    BASE(char n):c(n) {}
    virtual ~BASE() { cout<<c; }
};
class DERIVED:public BASE
{
private:
    char c;
public:
    DERIVED(char n):BASE(n+1),c(n) {}
    ~DERIVED(){ cout<<c; }
};
int main(){
    DERIVED d('X');
    return 0;
}

运行结果:

先析构派生类对象 后析构基类对象

时间: 2024-08-11 09:51:19

第13周 程序阅读-虚析构函数的相关文章

第13周 程序阅读-虚函数

#include<iostream> using namespace std; class A { int a; public: A():a(5){} virtual void print()const { cout<<a;} }; class B: public A { char b; public: B() { b='E'; } void print() const { cout<<b; } }; void show(A &x) { x.print(); }

第13周 程序阅读-纯虚函数

#include <iostream> using namespace std; class Base { public: virtual void Who() =0; }; class FirstDerived:public Base { public: void Who() { cout<<"F"; } }; class SecondDerived:public Base { public: void Who() { cout<<"S&

[CareerCup] 13.6 Virtual Destructor 虚析构函数

13.6 Why does a destructor in base class need to be declared virtual? 这道题问我们为啥基类中的析构函数要定义为虚函数.首先来看下面这段代码: class Foo { public: void f(); }; class Bar: public Foo { public: void f(); }; Foo *p = new Bar(); p->f(); 调用p->f()会调用基类中的f(),这是因为f()不是虚函数.为了调用派

第二周 程序阅读

#include <iostream> #include <cstring> using namespace std; class Student { private: int num; char name[20]; char sex; public: void set_data(int n, char *p,char s) { num=n; strcpy(name,p); sex=s; } void display( ) { cout<<"num: &quo

第九周 程序阅读-字符串类的设计

阅读下面的程序,领会其中用到的设计方案.技术手段与算法. /* 对于要定义的字符串类CMyString, 数据成员包括: - 字符串的长度: - 指向字符串第一个字符的指针 成员函数包括: - 不带参数的构造函数: - 带一个类型为const char *类型的参数(用于对字符串初始化)的构造函数: - 带一个const CMyString&类型的复制构造参数: - 析构函数: - Strlen函数 (用于求字符串的长度): - int Find(char c) (找出字符c在本字符串中第一次出

第九周-程序阅读理解

/*Copyright (c)2016,烟台大学计算机与控制工程学院 *All rights reserved. *文件名称:my.cpp *作 者:张瀚文 *完成日期:2016年5月6日 * *问题描述: 阅读程序,写出程序的运行结果并理解其运行机制. */ #include <iostream> #include<cstring> using namespace std; class A { char *a; public: A(char *aa) { a=new char[s

第九周-程序阅读

/*Copyright (c)2016,烟台大学计算机与控制工程学院 *All rights reserved. *文件名称:my.cpp *作 者:张瀚文 *完成日期:2016年5月6日 * *问题描述: 阅读程序,写出程序的运行结果并理解其运行机制. */ #include <iostream> #include<cstring> using namespace std; class A { char *a; public: A(A &t); A(char *aa) {

第15周 程序阅读-二进制文件及文件的读取1

1.阅读并运行下面的两个程序,分别用记事本和二进制文件阅读器(请自行下载Binary Viewer等程序,或者用DOS中的Debug程序,并百度其用法).查看其内容,并理解文件存储的原理. (1) #include <iostream> #include <fstream> #include <cstdlib> using namespace std; int main( ) { int a; ofstream outfile("f1.dat",io

第15周 程序阅读-二进制及二进制文件的读取3

3.阅读下面的程序,指出其功能,体会seekg().tellg()等函数的功能及其用法 (1) #include<iostream> #include <fstream> using namespace std; const char * filename = "a.txt"; int main () { long l,m; ifstream file (filename, ios::in|ios::binary); l = file.tellg(); file