求助
#include <iostream>using namespace std;
class Clock
{
public:
Clock(); // default constructor
Clock(int, int, int); // constructor
Clock(const Clock&);
~Clock();
void SetTime(int, int, int);
void ShowTime();
private:
int iHour;
int iMinute;
int iSecond;
};
Clock::Clock()
{
iHour = iMinute = iSecond = 0;
cout << "constructor1" << endl;
}
Clock::Clock(int h, int m, int s)
{
iHour = h;
iMinute = m;
iSecond = s;
cout << "constructor2" << endl;
}
Clock::Clock(const Clock &r) : iHour(r.iHour), iMinute(r.iMinute), iSecond(r.iSecond)
{
cout << "constructor3" << endl;
}
Clock::~Clock()
{
cout << "destrcutor" << endl;
}
void Clock::SetTime(int h, int m, int s)
{
iHour = h;
iMinute = m;
iSecond = s;
}
/*
为什么我将上面的函数改为:
void Clock::SetTime(int h, int m, int s) : iHour(h), iMinute(m), iSecond(s)
{}
时,编译会出错?
*/
void Clock::ShowTime()
{
cout << iHour << " : " << iMinute << " : " << iSecond << endl;
}
void f(Clock c)
{
c.ShowTime();
} // call Clock::~Clock() to destruct c
void g(Clock &c)
{
c.ShowTime();
}
Clock h()
{
Clock c(2, 13, 25);
c.ShowTime();
return c; // call Clock::Clock(const Clock&) to construct a return value object
}
int main()
{
Clock c1(13, 24, 23);
Clock c2 = c1; // call Clock::Clock(const Clock&)
c1.SetTime(10, 5, 16);
c1.ShowTime();
c2.ShowTime();
Clock *p;
p = new Clock(c2); // call Clock::Clock(const Clock&)
p->ShowTime();
delete p; // call Clock::~Clock to destruct the object pointed by p
cout << "------------" << endl;
f(c1); // call Clock::Clock(const Clock&)
cout << "------------" << endl;
g(c1);
cout << "------------" << endl;
Clock c3 = h();
cout << "-------------" << endl;
return 0; // call Clock::~Clock for 2 times to destruct c2 & c1
}