joeycbulk
February 1st, 2007, 12:28 PM
Hi! I'm reading this book from deitel & deitel and a part of this code I cant understand.
1: class Time {
2: public:
3: Time( int = 0, int = 0, int = 0 );
4: void setTime( int, int, int );
5: int getHour();
6: int &badSetHour( int );
7:private:
8: int hour;
9: int minute;
10: int second;
11: };
12: Time::Time( int hr, int min, int sec ) { setTime( hr, min, sec ); }
13: void Time::setTime( int h, int m, int s )
14: {
15: hour = ( h >= 0 && h < 24 ) ? h : 0;
16: minute = ( m >= 0 && m < 60 ) ? m : 0;
17: second = ( s >= 0 && s < 60 ) ? s : 0;
18: }
19: int Time::getHour() { return hour; }
20: int &Time::badSetHour( int hh )
21: {
22: hour = ( hh >= 0 && hh < 24 ) ? hh : 0;
23: return hour;
24: }
25: int main()
26: {
27: Time t;
28: t.badSetHour(12) = 74; //<<<<<<<<<<<
30: cout << t.getHour() << endl;
31: return 0;
32: }
At line 28 I was able to use t.badSetHour as an lvalue.
I dont know why the code was able to use it as an lvalue. Could some pls help me understand why... Thanks!
The book just told me not to use this reference return because I was able to assign an invalid value of 74.
1: class Time {
2: public:
3: Time( int = 0, int = 0, int = 0 );
4: void setTime( int, int, int );
5: int getHour();
6: int &badSetHour( int );
7:private:
8: int hour;
9: int minute;
10: int second;
11: };
12: Time::Time( int hr, int min, int sec ) { setTime( hr, min, sec ); }
13: void Time::setTime( int h, int m, int s )
14: {
15: hour = ( h >= 0 && h < 24 ) ? h : 0;
16: minute = ( m >= 0 && m < 60 ) ? m : 0;
17: second = ( s >= 0 && s < 60 ) ? s : 0;
18: }
19: int Time::getHour() { return hour; }
20: int &Time::badSetHour( int hh )
21: {
22: hour = ( hh >= 0 && hh < 24 ) ? hh : 0;
23: return hour;
24: }
25: int main()
26: {
27: Time t;
28: t.badSetHour(12) = 74; //<<<<<<<<<<<
30: cout << t.getHour() << endl;
31: return 0;
32: }
At line 28 I was able to use t.badSetHour as an lvalue.
I dont know why the code was able to use it as an lvalue. Could some pls help me understand why... Thanks!
The book just told me not to use this reference return because I was able to assign an invalid value of 74.