C++ 析构函数

2019-10-09  本文已影响0人  samtake

析构函数(destructor)是一种特殊的成员函数。

CreateAndDestructor::CreateAndDestructor(int ID, string msg){
    objectID = ID;
    message = msg;
    
    cout << "Object " << objectID << " 构造函数 runs  " <<message << endl;
}


void create(void){
    cout << "createFunc " << endl;
    CreateAndDestructor fifth(5, "(local automatic in create)");
    static CreateAndDestructor sixth(6, "(local automatic in create)");
    CreateAndDestructor seventh(7, "(local automatic in create)");
}

CreateAndDestructor::~CreateAndDestructor(){
    cout<<(objectID ==1 || objectID == 6 ? "\n" : "");
    
    cout << "Object " << objectID << " 析构函数 runs   " <<message << endl;
}


void testCreateAndDestructor(){
    cout << "testFunc " << endl;
    CreateAndDestructor second(2, "(local automatic in testFunc)");
    static CreateAndDestructor third(3, "(local automatic in testFunc)");
    
    create();
    
    
    cout << "testFunc : " << endl;
    
    CreateAndDestructor forth(4, "(local automatic in testFunc)");
    
    cout << "\ntestFunc end \n" << endl;
}

testFunc 
Object 2 构造函数 runs  (local automatic in testFunc)
Object 3 构造函数 runs  (local automatic in testFunc)
createFunc 
Object 5 构造函数 runs  (local automatic in create)
Object 6 构造函数 runs  (local automatic in create)
Object 7 构造函数 runs  (local automatic in create)
Object 7 析构函数 runs   (local automatic in create)
Object 5 析构函数 runs   (local automatic in create)
testFunc : 
Object 4 构造函数 runs  (local automatic in testFunc)

testFunc end 

Object 4 析构函数 runs   (local automatic in testFunc)
Object 2 析构函数 runs   (local automatic in testFunc)

Object 6 析构函数 runs   (local automatic in create)
Object 3 析构函数 runs   (local automatic in testFunc)
Program ended with exit code: 0
上一篇下一篇

猜你喜欢

热点阅读