目录:
1.关于运算符重载
运算符重载就是对现有的运算符重新定义,赋予其另一种功能,以实现不同的数据类型。其本质还是函数的重载,使用运算符重载可以使程序更清晰。运算符重载的关键字operator。C++绝大多数运算符都可以重载,不能重载的运算符有. :: .* ?: sizeof。
2.运算符重载的方式:成员函数和友元函数
友元函数:
(1)什么是友元函数
C++提供友元机制,允许一个类将其非公有成员的访问权授予指定的函数或类。通俗来讲,友元函数(或友元类)就像狗仔队,其它函数或类就像明星。狗仔队可以不经过明星的允许轻易知道明星私密的事情。
友元函数:如果在定义函数用friend关键字进行声明后,该函数就是友元函数。友元函数可以访问该类中的私有成员。此外,友元函数也可以是另一个类的成员函数,称为友元成员函数。
友元类:定义类时也可以用friend声明为友元类。两点说明:1.友元的关系是单向的,即如果B是A的友元类,不等于A是B的友元类,类A中的成员函数不能访问类B中的私有数据;2.友元的关系不能传递或继承。
(2)为什么要使用友元函数
面向对象程序设计的基本原则就是封装性和信息隐藏,而友元却可以随意访问其它类中的私有成员,突破了封装原则。使用友元,有助于信息共享,提高程序的运行效率,使用的时候要在数据共享与信息隐藏之间选择一个合适的平衡点。
3.只能用成员函数重载的运算符
运算符=,[],(),->只能通过成员函数来重载
原因:赞不清楚。。。
4.利用复数类实现运算符重载
(1)使用友元函数实现:
#include<iostream>
using namespace std;
class complex//定义虚数类,用成员函数实现符号重载
{
public:
complex(double r = 0, double i = 0);
friend complex operator +(const complex &c1,const complex &c2);
friend complex operator -(const complex &c1,const complex &c2);
friend complex operator -(const complex &c);
void print() const
{
cout << real << "+" << imag << "i" << endl;
}
private:
double real;
double imag;
};
complex::complex(double r, double i)//构造函数
{
real = r;
imag = i;
}
complex operator+(const complex &c1,const complex &c2)
{
complex c;
c.real = c1.real + c2.real;
c.imag = c1.imag + c2.imag;
return c;
}
complex operator-(const complex &c1,const complex &c2)
{
complex c;
c.real = c1.real - c2.real;
c.imag = c1.imag - c2.imag;
return c;
}
complex operator-(const complex &c)
{
return complex(-c.real, -c.imag);
}
int main()//定义主函数测试
{
complex c1(3, 5), c2(2, 7), c3;
c3 = c1 + c2;
c3.print();
c3 = c1 - c2;
c3.print();
c3 = -c1;
c3.print();
}
(2)使用成员函数实现:
#include<iostream>
using namespace std;
class complex//定义虚数类,用成员函数实现符号重载
{
public:
complex(double r = 0, double i = 0);
complex operator +(const complex &c2);
complex operator -(const complex &c2);
complex operator -();
void print()
{
cout << real << "+" << imag << "i" << endl;
}
private:
double real;
double imag;
};
complex::complex(double r, double i)//构造函数
{
real = r;
imag = i;
}
complex complex::operator+(const complex &c2)
{
complex c;
c.real = real + c2.real;
c.imag = imag + c2.imag;
return c;
}
complex complex::operator-(const complex& c2)
{
complex c;
c.real = real - c2.real;
c.imag = imag - c2.imag;
return c;
}
complex complex::operator-()
{
return complex(-real, -imag);
}
int main()//定义主函数测试
{
complex c1(3, 5), c2(2, 7), c3;
c3 = c1 + c2;
c3.print();
c3 = c1 - c2;
c3.print();
c3 = -c1;
c3.print();
}