C++ class内的 ++ 重载,左++,右++,重载示例。
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C++ class内的 ++ 重载,左++,右++,重载示例。,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2097字,纯文字阅读大概需要3分钟。
内容图文
#include <iostream> // overloading "operator ++ " inside class // ++ 是一元操作符 ////////////////////////////////////////////////////////// class Rectangle { public: Rectangle(int w, int h) : width(w), height(h) {}; ~Rectangle() {}; Rectangle& operator++ (); // ++i Rectangle operator++ (int); // i++ public: int width; int height; }; ////////////////////////////////////////////////////////// Rectangle & Rectangle::operator++ () { this->height++; this->width++; return *this; } // 返回类型不能是引用。为了使 i++ 的效果和默认类型一致 Rectangle Rectangle::operator++ (int) { Rectangle b(*this); ++(*this); return b; } ////////////////////////////////////////////////////////// std::ostream& operator<< (std::ostream& os, const Rectangle& rec) { os << rec.width << ", " << rec.height; return os; } ////////////////////////////////////////////////////////// int main() { Rectangle a(40, 10); Rectangle b = (a++); std::cout << "a = " << a << std::endl // 输出 41, 11 << "b = " << b << std::endl // 输出 40, 10 ; Rectangle c = (++a); std::cout << "a = " << a << std::endl // 输出 42, 12 << "b = " << b << std::endl // 输出 40, 10 << "c = " << c << std::endl // 输出 42, 12 ; std::cout << "a = " << a << std::endl // 输出 43, 13 << "a = " << ++a << std::endl // 输出 43, 13 ; std::cout << "a = " << (a++) << std::endl // 输出 43, 13 ; // C++ 自带的 ++ 作用结果 { int vint = 0; std::cout << "v = " << vint << std::endl; // 输出 0 std::cout << "v = " << vint << std::endl // 输出 1 << "v = " << vint++ << std::endl; // 输出 1 } { int vint = 0; std::cout << "v = " << vint << std::endl; // 输出 0 std::cout << "v = " << vint << std::endl // 输出 1 << "v = " << ++vint << std::endl; // 输出 1 } return 0; }
++i,应该是先自加一,返回自身(已经加1之后的自身);
i++,应该是先拷贝自身,再自加一,返回自身的拷贝(自己已经加1,但是拷贝没有)。
原文:https://www.cnblogs.com/alexYuin/p/11965428.html
内容总结
以上是互联网集市为您收集整理的C++ class内的 ++ 重载,左++,右++,重载示例。全部内容,希望文章能够帮你解决C++ class内的 ++ 重载,左++,右++,重载示例。所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。