注册 登录
编程论坛 C++教室

关于调用析构函数的问题,求教啊爱爱爱!

slfzzhm 发布于 2010-10-18 22:19, 621 次点击
#include<iostream>
using namespace std;
class goods{
private:
    static int totalweight;
    int weight;
public:
    goods(int w)
    {
        weight=w;
        totalweight+=w;
    }
    goods(goods&gd)
    {
        weight=gd.weight;
        totalweight+=weight;
    }
    ~goods()
    {
        totalweight-=weight;
    }
    int getwg()
    {
        return weight;
    }
    static int gettotal()
    {
        return totalweight;
    }
};
int goods::totalweight=0;
void main()
{
    int w ;   
    cout<<"the initial weight of goods:"<<goods::gettotal()<<endl;
    cin>>w;
    goods g1(w);//输入25
    cin>>w;
    goods g2(w);//输入60
    cout<<"the total weight of goods:"<<goods::gettotal()<<endl;
输出为the initial weight of goods:0
      the total weight of goods:85  
用类建立对象的时候不是会自动调用构造函数吗??但是对象消失的时候会自动调用析构函数,~goods()
    {
        totalweight-=weight;
    }
我的问题就是这道题目的对象在什么时候消失的???能不能帮我注释一下啊!
我的意思是输出应该是the initial weight of goods:0
                    the total weight of goods:0






}
6 回复
#2
hahayezhe2010-10-19 08:58
什么时候消失,看它是已什么形式创建的,当前作用域!
#3
slfzzhm2010-10-19 22:14
回复 2楼 hahayezhe
我不太明白啊,我不知道对象作用域到哪里结束啊?能帮我注释下到那一句话对象结束作用的呢????
#4
上官伊萱2010-10-20 15:35
把我们书上的例子给你
#include<iostream>
using namespace std;
#include <string>
class Student
{
public:
    Student(int n,string nam,char s)
    {
        num=n;
        name=nam;
        sex=s;
        cout<<"Constructor called."<<endl;
    }
    ~Student()  //定义析构函数
    {
        cout<<"Destructor called."<<endl;
    }
    void display()
    {
        cout<<"num:"<<num<<endl;
        cout<<"name:"<<name<<endl;
        cout<<"sex:"<<sex<<endl;
    }
private:
    int num;
    string name;
    char sex;
};

int main()
{
    Student stud1(10010,"wang_li",'f');
    stud1.display();
    Student stud2(10012,"zhang_fun",'m');
    stud2.display();
    return 0;
}
结果是:
  Constructor called.  (执行stud1的构造函数)
  num:10010 (执行stud1的display函数)
  name:wang_li
  sex:f

  Constructor called. (执行stud2的构造函数)
  num:10011  (执行stud2的display函数)
  name:zhang_fun
  sex:m
  Destructor called.(执行stud2的析构函数)
  Destructor called.(执行stud1的析构函数)

先构造的后析构,后构造的先析构。
#5
personallife2010-10-20 15:43
两个对象是在程序结束的时候 可以尝试在程序结束的时候输出内容看看
如:
void exit()
{
    cout<<"the total weight of goods:"<<goods::gettotal()<<endl;
    //在此设断点观察
}
void main()
{
    atexit(exit);
    int w ;   
    cout<<"the initial weight of goods:"<<goods::gettotal()<<endl;
    cin>>w;
    goods g1(w);//输入25
    cin>>w;
    goods g2(w);//输入60
    cout<<"the total weight of goods:"<<goods::gettotal()<<endl;
}

[ 本帖最后由 personallife 于 2010-10-20 15:44 编辑 ]
#6
myth_feng2010-10-20 18:01
同意2楼,看对象所在的作用域
goods g1(w);
goods g2(w);
都在main()中,只有当mian函数结束的时候才会调用析构函数。
#7
lyj2010lyj2010-10-20 19:15
以下是引用personallife在2010-10-20 15:43:20的发言:

两个对象是在程序结束的时候 可以尝试在程序结束的时候输出内容看看
如:
void exit()
{
    cout<<"the total weight of goods:"<
结束符相对应
1