c++运算符重载的方法提要
来源:互联网 发布:js qq客服代码 编辑:程序博客网 时间:2024/06/06 00:35
刚学了c++的运算符重载,为了方便自己复习,发一篇博客来看,希望各位大神给予指导,感激不尽。
//c++运算符重载的方法提要
#include<iostream>
using namespace std;
istream & operator>>(istream & is,ClassName &obj);
ostream & operator<<(ostream & os,const ClassName &obj);
class ClassName{
//重载 输入输出 >> << 要重载成全局的函数,并且在类中做友元声明。
friend istream & operator>>(istream & is,ClassName &obj);
friend ostream & operator<<(ostream & os,const ClassName &obj);
private:
int *p;
public:
//构造函数:
ClassName(){
p=new int[10];
for(int i=0;i<10;++i){
p[i]=i;
}
}
//拷贝构造函数:
ClassName(const ClassName & obj){
delete []p;
p=new int[10];
for(int i =0;i<10;++i){
p[i]=obj.p[i];
}
}
//析构函数:
~ClassName(){
delete [] p;
}
//重载+ - * / % 定义成全局函数会更灵活,可以做2+ClassObj这样的操作,但是现在就先定义成类方法吧。
ClassName operator+(const ClassName obj); //const 防止修改
ClassName operator-(const ClassName obj);
//就只写加减了其他一样。
//重载 == > < >= <= !=
bool operator==(const ClassName obj);
//其他一样。
//重载() []
//返回类型根据你的private来看
int operator[](int j){
return p[j];
}
//把当前对象当函数使用,得重载()运算符
ClassName operator()(int start,int end,int ln);
//重载= += -= *= /= 这些赋值运算符都必须重载为成员函数。
//用&来使return时不调用拷贝构造函数
ClassName &operator=(const ClassName &obj){
if(this=&obj)return *this;//防止自己复制自己
return *this;
}
//重载++ --
//有前置和后置两种,后置的要给个站位参数
//前置:
ClassName &operator++(){
//your operation
return *this;
}
//后置 :
ClassName &operator++(int x){
ClassName temp; //实现先赋值后做操作。
//operation
return temp;
}
//自定义类型转化函数
//operator 目标类型名() const {}
operator int()const{
//...
return ();//结果为目标类型的表达式
}
};
- c++运算符重载的方法提要
- c++-运算符的重载
- C++--运算符的重载
- 运算符的重载方法
- 运算符重载的方法
- [C/C++]运算符的重载
- C++-运算符重载
- [C++]重载运算符
- C#:运算符重载
- c++-++运算符重载
- C++:重载运算符
- 运算符重载(C++)
- [c++]运算符重载
- 【C++】运算符重载
- C++--------------------------------------------运算符重载
- C#:运算符重载
- C++:运算符重载
- C++:运算符重载
- GIT的深入理解与使用
- Uboot预备知识
- C++ 和lua交互学习的三个例子
- (c语言)在一个有数字的字符串中输出最长的数字
- PRML读书笔记——线性回归模型
- c++运算符重载的方法提要
- 选项卡控制器(tabBarController)基础
- 写给初学者22_android_百分比布局
- 二分图的最大匹配——匈牙利算法
- 【面试题】剑指Offer-50-求两个节点的最近公共祖先
- 二叉树的基本操作(严蔚敏)
- 深入理解LayoutInflater.inflate()
- JVM内存模型
- redis高级实用特性