如何在类中递增单独的变量,而不是对象本身?
How would I increment separate variables in a Class, instead of the object itself?
假设有一个类 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
相关文章:
- 你能重载对象变量名本身返回的内容吗
- 为什么我可以使用 memcpy 将一个对象变量复制到另一个对象变量
- 如何使用std::lower_bound比较对象变量,而不使用第二个对象进行比较
- 将私有对象变量与用户输入的变量进行比较
- 具有已定义操作重载的 C++ 非类型化值对象/变量库
- 如何对对象数组进行排序,而不考虑对象变量类型
- 在功能中设置对象变量
- 如何创建对象变量,以便每次分配新的指针
- C++ FileIO 以读取和写入对象变量
- 私下声明的对象变量的突变器/访问器方法
- C++ 列表中的对象变量在迭代过程中不会更新
- 稍后使用私有对象变量时如何初始化数组(初始化对象后)
- 通过向量更改对象变量的值
- C 全局对象变量内存释放
- 基本数据类型变量 VS 对象变量
- C 复制分配运算符,用于参考对象变量
- c++从列表中移除元素,并将其分配给对象变量
- 我们是否需要在C++中同步局部对象变量
- 点运算符和箭头运算符之间的区别 结构对象变量 在 C 或 C++ 中创建树
- 无法访问在 std 回调中传递的对象变量