一、类中类型转换函数重载
#include<iostream>
using namespace std;
#include<string>
class student
{
int idnum;
char name[20];
bool gender;
int age;
float grade_eng;
float grade_math;
float grade_phy;
float grade_cpp;
public:
student(int a, char *b, bool c, int d, float e, float f, float g, float h)
{idnum=a;strcpy(name,b);gender=c;age=d;grade_eng=e;grade_math=f;grade_phy=g;grade_cpp=h;}
void show()
{
cout<<"ID\tName\tSex\tAge\tEnglish\tMath\tPhysics\t\C++"<<endl;
cout<<idnum<<'\t'<<name<<'\t';
if(gender)
cout<<"Man\t";
else
cout<<"Woman\t";
cout<<age<<'\t'<<grade_eng<<'\t'<<grade_math<<'\t'<<grade_phy<<'\t'<<grade_cpp<<endl;
}
operator float()
{
return (grade_eng+grade_math+grade_phy+grade_cpp)/4;
}
};
void main()
{
student stu(20170101,"Zhangsan",true,20,90.1,80,75.4,100);
stu.show();
cout<<float(stu)<<endl;
}
二、字符串类中运算符重载
#include<iostream>
using namespace std;
#include<string.h>
class mystring
{
char *str;
public:
mystring(char *p)
{
str=new char[strlen(p)+1];
strcpy(str,p);
}
mystring(){str=NULL;}
~mystring() {delete []str;}
void show()
{
if(str)
cout<<str<<endl;
else
cout<<"This str is NULL!\n";
}
mystring operator =(mystring &a)
{
if(str)
{
cout<<"if str";
delete []str;
}
str=new char[strlen(a.str)+1];
strcpy(str,a.str);
return *this;
}
mystring & operator +=(mystring &a)
{
char *temp = new char[strlen(a.str)+strlen(str)+1];
strcpy(temp,str);
strcat(temp,a.str);
delete []str;
str=temp;
return *this;
}
mystring(mystring & a)
{
str=new char[strlen(a.str)+1];
strcpy(str,a.str);
}
friend bool operator ==(mystring &a,mystring &b);
};
bool operator ==(mystring &a, mystring &b)
{
if(strlen(a.str)!=strlen(b.str))
return false;
for(int i=0;i<strlen(a.str);i++)
if(a.str[i]!=b.str[i])
return false;
return true;
}
void main()
{
mystring a("张三");
a.show();
mystring b("李四");
b.show();
b+=a;
b.show();
mystring c(a);
cout<<(a==b)<<endl;
cout<<(a==c)<<endl;
}