operator+在类内与类外

class fg1
{

fg1 operator+(fg1 q)
{
this->a+=q.a;
return *this;
}//实现this+q;
//fg1 operator+(fg1 q,fg1 w);//类内只有左值的默认调用和右值的传入,该式错误
}
fg1 operator+ (fg1 a,int b)
{

}//类外可填两个满足a+b的数量要求,()内不能是两个相同的常见的类类型,如int,string等

operator<<只能在类外,仅要求一个参数。
···c++
ostream &operator<<(ostream &cout,fg1 d)
{
cout<<d.a;
return cout;
}//cout<<a<<b<<d;返回自己。用friend访问private数据
···

opreator++和operator(int)只能在类内

class fg1;
fg1 &operator++()
{
this->a++;
return *this;
}
fg1 &operator++(int)
{
fg1 temp;
temp=*this;
this->a++;
return temp;
}
int main();

operator=的深拷贝应用

class fg1
{
public:
int *a;
fg1(int f)
{
a=new int (f);
};
string s;
fg1 &operator=(fg1 a1)//由于默认的=会将两个对象的成员new进同一个空间,然后赋值,导致释放后指针悬挂(存在new的数据成员时)
//自定义一个operator=进行深拷贝
{
if(a!=NULL)
{
delete a;
a=NULL;
}
a=new int (*a1.a);
return *this;
}
};
int s();
int main()
{
fg1 q,z,x;
q=z=x;
}

关系运算符的重载(格式均统一),均可适用于类内和类外

class fg1
{
public:
fg1(){};
int a;
string s;
// int operator==(fg1 s)
// {
// if(this->a==s.a)
// return 1;
// else return 0;
// }
};
int operator==(fg1 s,fg1 d)
{
if(d.a==s.a)
return 1;
else return 0;
}

operator()的类内

class fg1
{
public:
fg1(){};
int a;
string s;
void operator()()
{
cout<<this->a;
}
};
int main()
{
fg1 q;
q();
}

over over!
wwssadad baba!