C++ ++ 和 -- 运算符重载

C++ 教程 · 2019-02-26 08:43:24

递增运算符( ++ )和递减运算符( -- )是 C++ 语言中两个重要的一元运算符。

下面的实例演示了如何重载递增运算符( ++ ),包括前缀和后缀两种用法。类似地,您也可以尝试重载递减运算符( -- )。

实例

#include <iostream> using namespace std; class Time { private: int hours; // 0 到 23 int minutes; // 0 到 59 public: // 所需的构造函数 Time(){ hours = 0; minutes = 0; } Time(int h, int m){ hours = h; minutes = m; } // 显示时间的方法 void displayTime() { cout << "H: " << hours << " M:" << minutes <<endl; } // 重载前缀递增运算符( ++ ) Time operator++ () { ++minutes; // 对象加 1 if(minutes >= 60) { ++hours; minutes -= 60; } return Time(hours, minutes); } // 重载后缀递增运算符( ++ ) Time operator++( int ) { // 保存原始值 Time T(hours, minutes); // 对象加 1 ++minutes; if(minutes >= 60) { ++hours; minutes -= 60; } // 返回旧的原始值 return T; } }; int main() { Time T1(11, 59), T2(10,40); ++T1; // T1 加 1 T1.displayTime(); // 显示 T1 ++T1; // T1 再加 1 T1.displayTime(); // 显示 T1 T2++; // T2 加 1 T2.displayTime(); // 显示 T2 T2++; // T2 再加 1 T2.displayTime(); // 显示 T2 return 0; }

当上面的代码被编译和执行时,它会产生下列结果:

H: 12 M:0
H: 12 M:1
H: 10 M:41
H: 10 M:42

点击查看所有 C++ 教程 文章: https://codercto.com/courses/l/18.html

查看所有标签

The Linux Command Line

The Linux Command Line

William E. Shotts Jr. / No Starch Press, Incorporated / 2012-1-17 / USD 39.95

You've experienced the shiny, point-and-click surface of your Linux computer-now dive below and explore its depths with the power of the command line. The Linux Command Line takes you from your very ......一起来看看 《The Linux Command Line》 这本书的介绍吧!

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具