//+,-,运算符重载
#include<iostream>
using namespace std;
class node
{
private:
int x,y;
public:
node(){};
node(int a,int b)
{
x=a,y=b;
}
init()
{
cin>>this->x>>this->y;
}
out()
{
cout<<x<<" "<<y<<endl;
}
node operator + (const node& b);
friend node operator - (const node& a,const node &b);//把全局函数定义为友元,函数需要访问x,y.
};
node node::operator + (const node & b)//成员重载函数
{
return node(x+b.x,y+b.y);//构造函数重载后,可以直接通过构造函数返回。
}
node operator - (const node& a,const node &b)//全局重载函数
{
return node(a.x-b.x,a.y-b.x);
}
int main()
{
int x,y;
node a,b,c;
a.init();
b.init();
c=a+b;
cout<<"a+b=";
c.out();
c=a-b;
cout<<"a-b=";
c.out();
}
/*
+,-,*,/,四个运算符重载方法基本相同,运算符为全局函数时,参数函数等于运算符
的目数,运算符为成员函数时,参数个数等于运算符的目数减一。
*/
//=运算符重载
#include<iostream>
#include<string.h>
using namespace std;
class String
{
private:
char *str;
public:
String operator = (const char *s)
{
if(str)
{
delete[]str;//如果str不为空,删除它,节省空间。
str=NULL;
}
if(s)
{
str=new char[strlen(s)+1];//为str开辟新内存,
strcpy(str,s);
}
return *this;//不写也行。
}
out()
{
cout<<str<<endl;
}
};
int main()
{
String a;
a="123456";
a.out();
}
/*
等号运算符重载方式和其他二元运算符重载方式基本相同,可需要实现的功能和其他
运算符有一些不同,需要注意空间释放等事项。
*/
//运算符重载为友元函数
#include<iostream>
using namespace std;
class node
{
private:
int x;
public:
node(){};
node(int a):x(a){};
node operator + (int a)//成员函数运算符重载
{
return node(a+x);
}
friend node operator + (int a,node b);//声明友元
out()
{
cout<<x<<endl;
}
};
node operator + (int a,node b)//全局运算符重载
{
return node(a+b.x);
}
int main()
{
node a(2);
a.out();
a=a+5;
a.out();
a=10+a;
a.out();
}
/*
有时候,为了实现一些特定的功能,需要把类的运算符重载成全局函数,而又需要保证类的密封性
不被破坏。一个类node,有时候希望node+5,5+node,这两个算式都解释的通,而node+5可以使用
类的重载来解释,可5+node呢?这时候就需要用到再次重载,重载为全局函数,全局函数无法访问类
的私有成员,这时候就需要用到friend来声明其函数为类的友元,便已访问类内的私有成员。
*/