c++ operatot重载
来源:互联网 发布:人脸识别算法代码 编辑:程序博客网 时间:2024/06/05 05:39
函数重载与返回值无关,如int foo()和 char foo()不能重载
//返回Interger的引用
Integer& Integer::operator=(int num){_num = num;return *this;}//Integer& Integer::operator=(Integer& other){_num = other._num;return *this;}int Integer::GetNum(){return _num;}Integer other;
other = demo = 100;等同于other.operator=(demo.operator=(100));
//一个空类有以下几项内容
class ClassDemo
{
public:
// 默认构造
// 默认析构
// 默认拷贝构造
// ClassDemo(const ClassDemo&other){}//默认为浅拷贝,需要深拷贝的业务需要自己重载。
// 默认赋值
// ClassDemo& operator=(const ClassDemo& other){}
// &默认取地址 retuen this一般不用动
// 默认operator&
// 默认operator*
//
};
//加了num之后默认拷贝改变、赋值改变,编译器会把它改变,默认以浅拷贝实现。
class ClassDemo
{private:
int _num;
public:
// 默认构造
// 默认析构
// 默认拷贝构造 功能函数
// ClassDemo(const ClassDemo&other){}//默认为浅拷贝,需要深拷贝的业务需要自己重载。
// 默认赋值
// ClassDemo& operator=(const ClassDemo& other){}
};
//深拷贝在对象中维护了所有参数的生命周期,所有参数的生命周期是我的对象的同步
MyString(const MyString& other)//重载默认拷贝函数,深拷贝示例{delete[]_str;_len = other._len;_str = new char[_len + sizeof(char)];strcpy(_str, other._str);}
//根据业务选择深浅拷贝!!!
//运算符重载
//可以重载的运算符 = > < == != + - & | ! new delete &取地址运算符 等
//不可以重载的运算符 :: ?:(三目运算) .(直接成员访问运算符) *.类成员指针运算符 siseof运算符
//拷贝构造函数
Integer::Integer(const Integer& other){_num = other._num;}
//重载operator=
Integer& Integer::operator=(int num){_num = num;return *this;} Integer& Integer::operator=(const Integer& other){_num = other._num;return *this;}
//重载operator+,返回Integer(内部temp的copy),外部可接收
Integer Integer::operator+(const Integer & other){Integer temp;temp = other._num+_num;std::cout << "temp(const Integer&)" << temp.GetNum() << std::endl;return temp;}
效果:demo + 100
//友元函数 ,虽然在class 里,但却是外部的,没有this 主要用于运算符重载
//friend Integer operator+(int num,Integer& me){Integer temp;temp = num + me._num;std::cout << "temp(int num, Integer&)" << temp.GetNum() << std::endl;return temp;}
效果:demo=100+demo
demo=100+demo +100 先调用friend 再调用operator+(int num)
//operator++()
//前++Integer Integer::operator++()//返回temp{Integer temp = *this;_num += 1;std::cout << "operator++()" << std::endl;return temp;}//后++Integer & Integer::operator++(int){_num += 1;std::cout << "operator(int)" << std::endl;return *this;}
//返回Integer 与Integer& 的区别:Integer会在返回值使用后析构,生成了个拷贝、Integer会先析构,再返回,所以无法返回。
//流运算符 << >>
friend std::ostream& operator<<(std::ostream& os, const Integer &me)//重载<<,返回ostream引用,ostream不让新建{os<<me._num;return os;//返回os的引用}friend std::istream & operator >> (std::istream & lhs, Integer & rhs){lhs >> rhs._num;return lhs;}
0 0
- c++ operatot重载
- C 重载
- C++<<重载
- C++-运算符重载
- C/C++ 函数重载
- [C++]重载运算符
- c++(重载、覆盖、隐藏)
- C语言的重载
- [c++]函数重载
- C++:函数重载
- Objective-C函数重载
- C符号重载
- c++(重载、覆盖、隐藏)
- c++(重载、覆盖、隐藏)
- c++(重载、覆盖、隐藏)
- c++(重载、覆盖、隐藏)
- c++(重载、覆盖、隐藏)
- C#:运算符重载
- 程序员面试金典: 9.5位操作 5.7寻找丢失的整数
- JSONP 教程
- 13.总线设备驱动模型(1)-总线设备驱动模型
- PHP JSON
- MySQL学习(三)
- c++ operatot重载
- AJAX 教程
- ArrayList分析
- AJAX 简介
- AJAX 实例
- AJAX - 创建 XMLHttpRequest 对象
- AJAX - 向服务器发送请求请求
- Android 消息机制
- AJAX - 服务器 响应