六十三. 左移右移操作符
#include <iostream>
using namespace std;
class Complex
{
public:
Complex(int a,int b)
{
this->a = a;
this->b = b;
}
void printComplex()
{
cout<<"("<<this->a<<","<<this->b<<"i)"<<endl;
}
Complex& operator+ (Complex &another) //注意operator与后面的操作符,必须中间没有空格,视operator为一个函数
{
this->a += another.a;
this->b += another.b;
return *this;
}
Complex& operator- (Complex & another)
{
this->a -= another.a;
this->b -= another.b;
return *this;
}
Complex & operator++()//重载的是前++运算符,类中实现
{
this->a ++;
this->b ++;
return *this;
}
const Complex operator++(int) //重载的是后++运算符,类中实现,亚元
{
Complex temp(this->a,this->b);
this->a++;
this->b++;
return temp;
}
friend ostream& operator<<(ostream &os, Complex &c);
friend istream & operator>>(istream &is, Complex &c);
//左移<<操作符只能写在全局,不能够写在成员方法中。否则调用的顺序会变反,会出现c1<<cout这样的情况,应当避免
#if 0
ostream& operator<<(ostream &os)//左移符号的重载,全局实现
{
os<<"("<<this->a<<","<<this->b<<"i)";
return os;
}
//右移>>操作符只能写在全局,不能够写在成员方法中。否则调用的顺序会变反,会出现c1>>cin这样的情况,应当避免
istream & operator>>(istream &is)
{
cout<<"a:";
is>>this->a;
cout<<"b:";
is>>this->b;
return is;
}
#endif
private:
int a;
int b;
};
ostream & operator<<(ostream &os, Complex &c)//左移<<符号的重载,全局实现
{
os<<"("<<c.a<<","<<c.b<<"i)";
return os;
}
istream & operator>>(istream &is, Complex &c)//右移>>符号的重载,全局实现
{
cout<<"a:";
is>>c.a;
cout<<"b:";
is>>c.b;
return is;
}
int main()
{
Complex c1(1,2);
Complex c2(2,4);
c1.printComplex();
c2.printComplex();
cin>>c1; //operator>>(cin,c1);
cout<<c1;
//cout<< c1<<" "<<c1; //operator<<(cout,c1);
return 0;
}
六十四.今日回顾和作业(略)
六十五. 昨日回顾(略)
六十六.等号操作符重载
#include <iostream>
#include <string.h>
using namespace std;
class Student
{
public:
Student()
{
this->id=0;
this->name = NULL;
}
Student(int id, char*name)
{
this->id = id;
int len=strlen(name);
this->name=new char[len+1];
strcpy(this->name,name);
}
Student(const Student& another)
{
this->id=another.id;
//深拷贝
int len = strlen(another.name);
this->name = new char[len+1];
strcpy(this->name,another.name);
}
Student& operator=(const Student &another)
{
//1. 防止自身赋值
if(this== &another)
return *this;
//2. 先将自身的额外开辟的空间回收掉
if(this->name != NULL){
delete[] this->name;
this->name=NULL;
this->id=0;
}
//3. 执行深拷贝
this->id=another.id;
int len=strlen(another.name);
this->name = new char[len+1];
strcpy(this->name,another.name);
return *this;
}
void PrintS()
{
cout<<"id:"<<id<<" "<<name<<endl;
}
~Student(){
if(this->name != NULL){
delete[] this->name;
this->name = NULL;
this->id=0;
}
}
private:
int id;
char *name;
};
int main()
{
Student s1(1,"zhang3");
Student s2=s1;
s1.PrintS();
s2.PrintS();
Student s3(2,"li4");
s2=s3;//s2 = 赋值操作符
s1.PrintS();
s2.PrintS();
s3.PrintS();
return 0;
}