c 内类的运用
1.计算时间
代码语言:javascript复制#include
using namespace std;
class Time
{
private:
int hours;
int minutes;
public:
Time();
Time(int h, int m = 0);
void AddMin(int m);
void AddHr(int h);
void Reset(int h = 0, int m = 0);
Time Sum(const Time& t) const;
void Show() const;
};
Time::Time()
{
hours = minutes = 0;
}
Time::Time(int h, int m)
{
hours = h;
minutes = m;
}
void Time::AddMin(int m)
{
minutes = m;
hours = minutes / 60;
minutes %= 60;
}
void Time::AddHr(int h)
{
hours = h;
}
void Time::Reset(int h, int m)
{
hours = h;
minutes = m;
}
Time Time::Sum(const Time& t) const
{
Time sum;
sum.minutes = minutes t.minutes;
sum.hours = hours t.hours sum.minutes / 60;
sum.minutes %= 60;
return sum;
}
void Time::Show() const
{
std::cout << hours << " hours, " << minutes << " minutes";
}
int main()
{
using std::cout;
using std::endl;
Time planning;
Time coding(2, 40);
Time fixing(5, 55);
Time total;
cout << "planning time = ";
planning.Show();
cout << endl;
cout << "coding time = ";
coding.Show();
cout << endl;
cout << "fixing time = ";
fixing.Show();
cout << endl;
total = coding.Sum(fixing);
cout << "coding.Sum(fixing) = ";
total.Show();
cout << endl;
return 0;
}
这是一串简单的类代码,比较重要的是sum()函数,注意到了参数是引用但是返回类型不是引用。将参数声明作为引用的目的只是为了提高效率,传递引用速度更快,使用的内存更少。 看一下输出内容QAQ
代码语言:javascript复制planning time = 0 hours, 0 minutes
coding time = 2 hours, 40 minutes
fixing time = 5 hours, 55 minutes
coding.Sum(fixing) = 8 hours, 35 minutes
接下来我们要在类里面添加加法运算符“ ” 我们只修改主函数和sum()函数声明,其他的都是一样的。
代码语言:javascript复制include <iostream>
using namespace std;
int main()
{
using std::cout;
using std::endl;
Time planning;
Time coding(2, 40);
Time fixing(5, 55);
Time total;
cout << "planning time = ";
planning.Show();
cout << endl;
cout << "coding time = ";
coding.Show();
cout << endl;
cout << "fixing time = ";
fixing.Show();
cout << endl;
total = coding fixing;
// operator notation
cout << "coding fixing = ";
total.Show();
cout << endl;
Time morefixing(3, 28);
cout << "more fixing time = ";
morefixing.Show();
cout << endl;
total = morefixing.operator (total);
// function notation
cout << "morefixing.operator (total) = ";
total.Show();
cout << endl;
return 0;
}
operator ()也是由Time对象调用的,第二个Time的对象作为参数,斌且返回一个Time对象。因此可以用sum()方法调用。 运算符重载非常好用,但是也有许多限制,下一章来叙述。