C++:运算符重载为类的有元函数以及运算符重载为类的成员函数,虚函数

运算符重载为类的有元函数以及运算符重载为类的成员函数 举例代码:

#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,讲师

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值