如何在类中递增单独的变量,而不是对象本身?

How would I increment separate variables in a Class, instead of the object itself?

本文关键字:对象 变量 单独      更新时间:2023-10-16

假设有一个类 Time,它包含三种数据类型小时、分钟和秒。使用运算符重载,我将如何分别递增这三个变量?

下面是一个计数器示例,显示了使用 ++ 运算符递增如何完全递增所有变量。我想单独或仅增加一个。但是我不知道如何通过对象访问它们

class Time
{
private:
int Hour, Minute, Second, option;
public:
Time() : Hour(13), Minute(59), Second(59)
{
}
void operator ++ ()
{
++Second;
++Minute;
++Hour;
}
void Display ()
{
cout << Hour << ":" << Minute << ":" << Second << endl;
}
};
int main ()
{
Time t;
++t;
t.Display();
return 0;
}

创建一个具有一些公共属性的类

class Time {
public:
int hour = 0;
int minute = 0;
int second = 0;
};

,然后创建 Time 的实例并更新属性

Time time = Time();
// assign whatever value you like
time.hour = 2;
time.minute = 32;
time.second = 324;
// or use the increment operator
time.hour++
// time.hour now contains the value 3