运算符重载为类的有元函数以及运算符重载为类的成员函数 举例代码:
#include<iostream>
#include<cmath>
using namespace std;
class complex
{
double real,image;
public:
complex(double r=0,double i=0)
{
real=r;image=i;
}
friend complex operator+(complex c1,complex c2); //运算符重载为类的有元函数
/*{
return complex(real+c.real,image+c.image);
}*/
complex operator-(complex c) //运算符重载为类的成员函数
{
return complex(real-c.real,image-c.image);
}
void print()
{
cout<<"("<<real<<(image>0?'+':'-')<<fabs(image)<<"i)\n";
}
};
complex operator+(complex c1,complex c2)
{
return complex(c1.real+c2.real,c1.image+c2.image);
}
int main()
{
complex c1(4,2),c2(2.2,4.3),c3,c4,c5,c6;
cout<<"c3=";
c3=c1+c2;
c3.print();
cout<<"c4=";
c4=operator+(c1,c2);
c4.print();
cout<<"c5=";
c5=c1-c2;
c5.print();
cout<<"c6=";
c6=c1.operator-(c2);
c6.print();
}
运行结果:
c3=(6.2+6.3i)
c4=(6.2+6.3i)
c5=(1.8-2.3i)
c6=(1.8-2.3i)
虚函数:
#include<iostream>
using namespace std;
class person
{
public:
string name;int age;
person(string n,int a){name=n;age=a;}
virtual void sayhi()
{
cout<<name<<","<<age<<endl;
}
} ;
class student:public person
{
public:
string hobby;
student(string n,int a,string h):person(n,a){hobby=h;}
void sayhi()
{
cout<<name<<","<<age<<hobby<<endl;
}
};
class teacher:public person
{
public:
string level;
teacher(string n,int a,string le):person(n,a)
{
level=le;
}
void sayhi()
{
cout<<name<<","<<age<<","<<level<<endl;
}
};
main()
{
student s1("陈",20,"阅读");
teacher t1("陆",30,"讲师");
person *p1=&s1;
p1->sayhi();
p1=&t1;
p1->sayhi();
}
运行结果:
陈,20阅读
陆,30,讲师