c++运算符重载
2016-07-30 09:14
246 查看
以下示例中定义了一个class test, 重载了<, +, +=, =, ==, <<, >>等符号:
#include<iostream>
#include<vector>
using namespace std;
class test{
public:
int v;
test():v(0){}
test(const int &a):v(a){}
test(const test &t1):v(t1.v){}
//比较两个对象的大小
bool operator<(const test &t1) const{
return (v < t1.v);
}
//比较对象和int的大小
bool operator<(const int &t1) const{
return (v < t1);
}
//友元函数,比较int和对象的大小
friend inline bool operator<(const int &a, const test & t1){
return (a < t1.v);
}
//对象间赋值
test & operator=(const test &t1){
v = t1.v;
return *this;
}
//int赋值给对象
test & operator=(const int &t1){
v = t1;
return *this;
}
//对象加上 int
test operator+(const int & a){
test t1;
t1.v = v + a;
return t1;
}
//对象加对象
test operator+(test &t1){
test t2;
t2.v = v + t1.v;
return t2;
}
//对象加上对象
test &operator+=(const test &t1){
v += t1.v;
#include<iostream>
#include<vector>
using namespace std;
class test{
public:
int v;
test():v(0){}
test(const int &a):v(a){}
test(const test &t1):v(t1.v){}
//比较两个对象的大小
bool operator<(const test &t1) const{
return (v < t1.v);
}
//比较对象和int的大小
bool operator<(const int &t1) const{
return (v < t1);
}
//友元函数,比较int和对象的大小
friend inline bool operator<(const int &a, const test & t1){
return (a < t1.v);
}
//对象间赋值
test & operator=(const test &t1){
v = t1.v;
return *this;
}
//int赋值给对象
test & operator=(const int &t1){
v = t1;
return *this;
}
//对象加上 int
test operator+(const int & a){
test t1;
t1.v = v + a;
return t1;
}
//对象加对象
test operator+(test &t1){
test t2;
t2.v = v + t1.v;
return t2;
}
//对象加上对象
test &operator+=(const test &t1){
v += t1.v;
相关文章推荐
- C++运算符重载基础
- c++运算符重载字符串想加
- C++运算符重载讲解与经典实例
- C++运算符重载:operator
- C++运算符重载补充之不同数据间的类型转换
- C++运算符重载的方法详细解析
- C++运算符重载讲解与经典实例(转自千里冰封网友)
- 为什么有时候C++运算符重载要返回引用,附对象生存周期
- 【ZZ】C++运算符重载总结 & 返回值优化
- C++运算符重载补充之不同数据间的类型转换
- C++运算符的重载
- c++运算符重载、类型转换函数总结
- C++运算符重载
- C++运算符重载(4) .*和.->操作符介绍
- 第十七周oj刷题——Problem A: 实现复数类中的加运算符重载【C++运算符重载】
- C++运算符重载(成员函数方式)
- C++运算符重载探讨
- C++运算符重载
- C++运算符重载讲解与经典实例
- c++运算符的重载