C++ 操作符重载
2013-10-11 19:59
337 查看
1、为什么要使用操作符重载?
操作符和方法在本质上一样,使用操作符更符合人性化的描述。
2、操作符重载分为 普通操作符重载和成员操作符重载,区别在于:
a、普通操作符重载要访问对象的私有成员,因此要设计为friend,而成员操作符重载不需要;
b、相比于普通操作符重载,成员操作符重载,少了一个形参,因为成员方法总是与对象绑定使用的,被绑定的对象就是操作符的第一个参数;
示例代码:
View Code
操作符和方法在本质上一样,使用操作符更符合人性化的描述。
2、操作符重载分为 普通操作符重载和成员操作符重载,区别在于:
a、普通操作符重载要访问对象的私有成员,因此要设计为friend,而成员操作符重载不需要;
b、相比于普通操作符重载,成员操作符重载,少了一个形参,因为成员方法总是与对象绑定使用的,被绑定的对象就是操作符的第一个参数;
示例代码:
#include "StdAfx.h" #include <iostream> #include "Point.h" Point ::Point() { } Point::Point(int x,int y) { this->x = x; this->y = y; } void Point::Print()const { std::cout<<"X:"<<x<<" Y:"<<y<<std::endl; } Point operator+(const Point& a,const Point& b) { Point s(a.x+b.x,a.y+b.y); return s; } Point operator+(const Point& a,int b) { Point s(a.x+b,a.y+b); return s; } void Point::Set(int x,int y) { this->x = x; this->y = y; }
View Code
相关文章推荐
- C++中的操作符重载
- 再看C++(6)--操作符重载
- C++输入输出操作符重载
- C++ 操作符重载(3) 什么时候需要自定义赋值操作符
- C++ operator overload -- 操作符重载
- C++ 模板类友元之输出流操作符重载
- C++ 操作符重载
- C++ 运算符流操作符重载和友元--笔记
- C++中关于操作符重载诸多问题
- C++随笔——操作符重载
- C++中的操作符重载
- c++ base-操作符重载
- C++基础学习笔记----第十三课(操作符重载-下)
- 【C++】C++中的操作符重载
- C++语法之操作符重载函数
- C++输入输出操作符重载
- 【C++第八课】---操作符重载上
- 操作符重载C++
- C++ 基础编程之十进制转换为任意进制及操作符重载
- C++:操作符重载