C++重载运算符
来源:互联网 发布:mac如何设置iphone铃声 编辑:程序博客网 时间:2024/06/08 01:26
本文主要讲述加号运算符“+”,自增运算符“++”,流提取运算符运“>>”,流插入运算符"<<"的重载。
先给出Vector类:
class Vector{ public: Vector(double a = 0, double b = 0) {x = a, y = b;} //构造函数 Vector(const Vector& v){x = v.x, y = v.y;} //拷贝构造函数 Vector operator + (const Vector& v); //重载+ Vector operator ++ (); //重载前置自增运算符“++” Vector operator ++ (int); //重载后置自增运算符“++” friend istream& operator >> (istream& input, Vector& v); //重载“>>” friend ostream& operator << (ostream& output, Vector& v); //重载“<<” private: double x; double y;};
1.重载加号
代码实现
Vector Vector::operator + (const Vector& v){ return Vector(x + v.x, y + v.y); //此处调用拷贝构造函数};
“/”、“*”、“-”的重载类似。
2.重载自增运算符
自增运算符分为前置和后置两种。对于前置自增,重载函数返回自增后的对象,对于后置自增,重载函数返回自增前的对象。为了区分,C++规定,在对自增运算符进行重载时,若额外加上一个int型形参,就表明重载的是后置自增。
(1)前置自增
Vector Vector::operator ++ (){ ++x; ++y; return *this;};
(2)后置自增
Vector Vector::operator ++ (int){ Vector temp(*this); x++; y++; return temp;};
“--”的重载类似。
3.“>>”和“<<”
前面的运算符均重载为类的成员函数,但是对于流插入和流提取运算符却不能如此,而是重载为类的友元函数。
“>>”重载
istream& operator >> (istream& input, Vector& v){ cout << "x: "; input >> v.x; cout << "y: "; input >> v.y; return input;};
“<<”重载
ostream& operator << (ostream& output, Vector& v){ output << "Vector:" << "(" << v.x << "," << v.y << ")"; return output;};
以下是完整的程序:
#include <iostream>using namespace std;class Vector{ public: Vector(double a = 0, double b = 0) {x = a, y = b;} Vector(const Vector& v){x = v.x, y = v.y;} Vector operator + (const Vector& v); Vector operator ++ (); Vector operator ++ (int); friend istream& operator >> (istream& input, Vector& v); friend ostream& operator << (ostream& output, Vector& v); private: double x; double y;};Vector Vector::operator + (const Vector& v){ return Vector(x + v.x, y + v.y); //此处调用拷贝构造函数};Vector Vector::operator ++ (){ ++x; ++y; return *this;};Vector Vector::operator ++ (int){ Vector temp(*this); x++; y++; return temp;};istream& operator >> (istream& input, Vector& v){ cout << "x: "; input >> v.x; cout << "y: "; input >> v.y; return input;};ostream& operator << (ostream& output, Vector& v){ output << "Vector:" << "(" << v.x << "," << v.y << ")"; return output;};int main(){ Vector v1, v2; cin >> v1 >> v2; v1++; ++v2; cout << v1 << endl << v2 << endl; return 0;}
运行:
- C++-运算符重载
- [C++]重载运算符
- C#:运算符重载
- c++-++运算符重载
- C++:重载运算符
- 运算符重载(C++)
- [c++]运算符重载
- 【C++】运算符重载
- C++--------------------------------------------运算符重载
- C#:运算符重载
- C++:运算符重载
- C++:运算符重载
- C#:运算符重载
- [C++]运算符重载
- 【c++】运算符重载
- C++:运算符重载
- C#:运算符重载
- C++:运算符重载
- IE8/9下,text-indent对css描绘三角形的影响
- hadoop的常用参数
- typedef数组类型
- [LeetCode] SUM4
- 格式化数字
- C++重载运算符
- Oracle 表空间联机(online)与脱机(offline)
- [Cadence]学习笔记1——update cache的问题
- oracle表空间操作详解
- Project Euler problem 41
- makefile之编译参数
- 检测内存泄露的方法
- 数学的力量(二)
- kindle 5 任意订阅自动定期推送 Rss/网页/新闻 详细解决方案