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

输出结果和书上的不一样,求解(新手不知道如何累积点数,20点是我的家底,还望各位海涵)

陈小昱 发布于 2016-05-30 16:36, 4209 次点击
目前正在自学c++,照著书中范例打完如下
#include<iostream>
using namespace std;
class Time                                                                                          
{     
    public:
        Time();
        Time(int,int,int);
        void settime(int,int,int);
        void sethour(int);
        void setminute(int);
        void setsecond(int);
        void printtime();
        ~Time();
    private:                              
        int hour;
        int minute;
        int second;
        
};

Time::Time()  
{
   
    cout<<"call constructor."<<endl;
    hour=minute=second=0;
}

Time::Time(int h,int m,int s)   
{         
    cout<<"call constructor with reference."<<endl;
    hour=(h>0&&h<24)?h:0;
    minute=(m>0&&m<60)?m:0;
    second=(s>0&&s<60)?s:0;
}

void Time::settime(int h,int m,int s)
{
    hour=(h>0&&h<24)?h:0;
    minute=(m>0&&m<60)?m:0;
    second=(s>0&&s<60)?s:0;
}

void Time::sethour(int h)
{hour=(h>0&&h<24)?h:0;}
void Time::setminute(int m)
{minute=(m>0&&m<60)?m:0;}
void Time::setsecond(int s)
{second=(s>0&&s<60)?s:0;}
void Time::printtime()
{cout<<(hour<10?"0":"")<<hour<<":"<<(minute<10?"0":"")<<minute<<
 ":"<<(second<10?"0":"")<<second<<endl;}
Time::~Time()
{cout<<"call destructor!"<<endl;}

int main()
{
    Time t1,t2(13,20,25);
   
    cout<<"t1 is:";
    t1.printtime();
    cout<<"t2 is:";
    t2.printtime();
   
    t1.settime(13,30,0);
    cout<<"reset t1 is:";
    t1.printtime();
   
    t2.sethour(8);
    cout<<"reset t2 is:";
    t2.printtime();
   
    return 0;
}
输出结果应为:
call constructor.
call constructor with reference.
t1 is:00:00:00
t2 is:13:20:25
reset t1 is:13:30:00
reset t2 is:08:20:25

可是我自己执行的结果是:
call constructor.
call constructor with reference.
t1 is:00:00:00
t2 is:13:20:25
reset t1 is:13:30:00
reset t2 is:08:20:25
call destructor!
call destructir!

本以为把
Time::~Time()
{cout<<"call destructor!"<<endl;}
删除之后即可
结果删除之后根本无法执行
这又是为什么呢?

[此贴子已经被作者于2016-5-30 16:37编辑过]

9 回复
#2
a95806432016-05-30 17:52
只有本站会员才能查看附件,请 登录

运行结果
#3
yangfrancis2016-05-30 21:29
最后打印出那两条信息也没什么妨碍啊。为什么非得不要?想丢掉那两句也很好办。把~Time里面的cout语句改成一个分号就是了
#4
rjsp2016-05-31 08:13
有构造当然就得有析构,也不知道你为什么说“输出结果应为……”?
#5
陈小昱2016-05-31 09:08
回复 2楼 a9580643
所以您的输出结果是正确的!!!!意思是输出结果不同只是因为编译器不同吗?
#6
陈小昱2016-05-31 09:12
回复 3楼 yangfrancis
请问您的意思是改成这样么? 可是我这样改了之后无法执行...
Time::~Time()
{call destructor!;}
#7
yangfrancis2016-05-31 09:13
Time::~Time()
{;}
这样
#8
陈小昱2016-05-31 09:18
回复 4楼 rjsp

"结果应为"是书上范例写的输出结果,
不好意思~我自学c++中"类别与物件"这个单元,还不太清楚,请问一下
析构是什么?
#9
陈小昱2016-05-31 09:52
回复 7楼 yangfrancis
成功了!!只是为什么我在int main()大括号中并没有呼叫~Time()却仍会列印出来啊?
#10
仰望星空的2016-06-01 19:19
析构函数是自动调用的,生成对象后,在对象消亡时候,就会调用到析构函数~
1