您的位置:首页 > 其它

拷贝构造与重载运算符

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";
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: