拷贝构造与重载运算符
2016-04-30 14:03
399 查看
C++学习笔记之四
1.拷贝运算符
含义:以一个对象为蓝本来构造另一个函数。
上一节已经讲到了拷贝函数的三种形式:
(1)Object a;
Object b(a);//等同于:Object b=a;
(2) 动态创建:Object *p=new Object(a);
(3)函数传值调用:void test(Object a);
会自动调用Object(const Object &other){this->a=other.a;}
系统有默认的,如没有必要,不要写。
Text(const text &other){
m_size=oher.m_size;
m_buff=new char[m_size];
strcopy(m_buf,other.m_buf);
}//拷贝其数据而不是拷贝其指针,用这种情况。
浅拷贝:m_buf=other.m_buf;
小结:只有在拷贝其数据的情况下,才需要深度拷贝。
friend成员:
访问类的任何成员,不受private,protected限制。
2.重载运算符
1)重载加减运算符。
Object operator +(Const Object &other){
return ?
}
2)重载[]运算符
char &operator[](int index){
return m_buff[index];
}
3)重载关系操作符(>=、==)
bool operator ==(cost Object & object){
}
bool operator ==(cost Object & object1,Const Object &obj2){
}
4重载类型转换符
operator Type(){
}
operator double(){
return double(num/den);
}
double(fla);
operator const char *(){
return m_buf;
}
Text t1("HelloWorld");
const char *txt=(const char *)t1;
printf("%s\n",txt);
5)重载输入输出操作符
格式:类类型 & operator <<(类型名 值)
logger & operator <<(int value){
printf("%d\n',value);
return *this;
}
返回引用(&)或左值,可以将其串起来。
logger lg;
lg<<1<<"Hello";
1.拷贝运算符
含义:以一个对象为蓝本来构造另一个函数。
上一节已经讲到了拷贝函数的三种形式:
(1)Object a;
Object b(a);//等同于:Object b=a;
(2) 动态创建:Object *p=new Object(a);
(3)函数传值调用:void test(Object a);
会自动调用Object(const Object &other){this->a=other.a;}
系统有默认的,如没有必要,不要写。
Text(const text &other){
m_size=oher.m_size;
m_buff=new char[m_size];
strcopy(m_buf,other.m_buf);
}//拷贝其数据而不是拷贝其指针,用这种情况。
浅拷贝:m_buf=other.m_buf;
小结:只有在拷贝其数据的情况下,才需要深度拷贝。
friend成员:
访问类的任何成员,不受private,protected限制。
2.重载运算符
1)重载加减运算符。
Object operator +(Const Object &other){
return ?
}
2)重载[]运算符
char &operator[](int index){
return m_buff[index];
}
3)重载关系操作符(>=、==)
bool operator ==(cost Object & object){
}
bool operator ==(cost Object & object1,Const Object &obj2){
}
4重载类型转换符
operator Type(){
}
operator double(){
return double(num/den);
}
double(fla);
operator const char *(){
return m_buf;
}
Text t1("HelloWorld");
const char *txt=(const char *)t1;
printf("%s\n",txt);
5)重载输入输出操作符
格式:类类型 & operator <<(类型名 值)
logger & operator <<(int value){
printf("%d\n',value);
return *this;
}
返回引用(&)或左值,可以将其串起来。
logger lg;
lg<<1<<"Hello";
相关文章推荐
- Java基础 - 欧几里得法求最大公约数
- 玩转Google开源C++单元测试框架Google Test系列(gtest)(总)
- 第四次上机作业
- win快捷键大全
- [三进制倍增 || 可并堆] BZOJ 4003 [JLOI2015]城池攻占
- Linux内核学习总结
- POJ3422 Kaka's Matrix Travels
- golang协程资源占有率
- HDOJ(HDU) 2091 空心三角形
- HDOJ(HDU) 2091 空心三角形
- Java重载(OverLoad)的理解
- php file_put_contents() 读取数据不换行问题
- Java的对象是采用值传递还是引用传递?
- 发表在IBM Developworks上的文章,Spark Streaming 图片处理案例介绍
- 面试中的排序算法总结
- 排序问题-快速排序
- [乱搞 暴力 并查集] BZOJ 3563 DZY Loves Chinese
- poj 2777 Count Color(线段树区间更新+位运算)
- Codeforces Round #349 (Div. 2) - C
- Shell编程入门总结(三)