首页 > 技术文章 > C++003类的析构函数

xieyi-1994 2020-11-21 18:08 原文

类的析构函数是类的一种特殊的成员函数,它会在每次删除所创建的对象时执行。

析构函数的名称与类的名称是完全相同的,只是在前面加了个波浪号(~)作为前缀,它不会返回任何值,也不能带有任何参数。

析构函数有助于在跳出程序(比如关闭文件、释放内存等)前释放资源。

// 类定义
// stock00.h

#ifndef STOCH00_H_
#define STOCH00_H_

#include<string>
using namespace std;

class Stock {
    private:
        std::string company;
        long shares;
        double share_val;
        double total_val;

        void set_tot() { total_val = shares * share_val; } // 内联函数
    public:
        Stock(const string & co, long n = 0, double pr = 0.0); // 构造函数
        ~Stock();// 析构函数

        void acquire(const std::string & co, long n, double pr);
        void buy(long num, double price);
        void sell(long num, double price);
        void update(double price);
        void show();
};


#endif

 

// 成员函数实现
// stock00.cpp

#include<iostream>

#include "stock00.h"


void Stock::acquire(const std::string & co, long n, double pr) {
    company = co;
    if (n < 0) {
        std::cout << "Number of shares can't be negative;"
            << company << "shares set to 0.\n";
    }
    else {
        shares = n;
    }
    share_val = pr;
    set_tot();
}
void Stock::buy(long num, double price) {
    if (num < 0) {
        std::cout << "Number of shares purchased can't be negative."
            << "Transaction is aborted.\n";
    }
    else {
        shares += num;
        share_val = price;
        set_tot();
    }
}
void Stock::sell(long num, double price) {
    using std::cout;
    if (num < 0) {
        cout << "Number of shares sold can't be negative."
            << "Transaction is aborted.\n";

    }
    else if(num > shares){
        cout << "You can't sell more than you have!"
            << "Transaction is aborted.\n";
    }
    else {
        shares -= num;
        share_val = price;
        set_tot();
    }
}
void Stock::update(double price) {
    share_val = price;
    set_tot();
}
void Stock::show() {
    std::cout << " Company: " << company<<'\n'
        << " Shares: $" << shares << '\n'
        << " Share Price: $" << share_val<<'\n'
        << " Total Worth: $" << total_val << '\n';
}

// 构造函数
Stock::Stock(const string & co, long n, double pr) {
    company = co;
    if (n < 0) {
        std::cerr << "Number of shares can't be negative; "
            << company << " shares set to 0.\n";
        shares = 0;
    }
    else {
        shares = n;
    }
    share_val = pr;
    set_tot();
}

// 析构函数
Stock::~Stock() {
    cout << "\nBye, " << company << "!\n";
}

 

// 类的使用
// usestock0.cpp

#include<iostream>

#include "stock00.h"

int main() {
    Stock fluffy_the_cat("NanoSmart", 20, 12.50); 
    fluffy_the_cat.show();

    return 0;
}

 

推荐阅读