2016-05-29 87 views
3
#include <iostream> 
using namespace std; 

class teacher{ 
private: 
    int Tnum; 
public: 

    teacher(){ 
     Tnum = 0; 
    } 
    teacher(int n){ 
     cout << "creating teacher"<<endl; 
     Tnum = n; 
    } 
    ~teacher(){ 
     cout << "destroying teacher" << endl; 

    } 
}; 

class student: public teacher{ 

private: 
    int Snum; 

public: 
    student(){ 
     Snum =0; 
    } 

    student(int n){ 
     cout << " creating student"<<endl; 
     Snum = n; 
    } 
    ~student(){ 
     cout << "destroying student"<<endl; 
     teacher t(1); 
     cout << "teacher created"<<endl; 
    } 
}; 

int main(){ 

    teacher t(20); 
    student s(30); 

} 
+0

C++允许你这样做,但它根本没有任何意义。你想做什么? – ConsistentProgrammer

+0

那么,它可以说是有道理的。例如,您可以创建一个类的实例,将更改写入数据库。当然,你有一个问题就是创建一个对象可能会抛出一个异常,并且*析构函数不应该抛出*。 –

回答

3

你展示了一个编译的例子。怎么了?
它的行为就像在任何其他函数中创建的对象,并且一旦超出范围就会被销毁。

12.4p8我们发现:

执行析构函数的身体和破坏人体内部分配的任何自动对象后[...]

这证实了创建中的对象析构函数的主体是合法的。

但是,要小心!如果这些对象的构造函数抛出异常,它可能会伤害到你,因为析构函数是非抛出的,遇到异常会导致应用程序终止。

+1

值得明确指出,析构函数只是一个函数,当对象被销毁时它会被自动调用。除了缺少返回类型和'noexcept'外,它只是一个函数。 – Kittsil

+0

或多或少。它属于标准的[特殊成员函数](http://eel.is/c++draft/#special)部分。无论如何,我明白你的意思。 – skypjack

相关问题