C++类和对象的概述(中)
四:函数重载和运算符重载
(一)函数重载:
函数重载是指在一个类中,可以声明几个功能类似的同名函数,但是这些同名函数的形式参数(指参数的个数、参数的类型)必须不同。函数重载的好处是增加了程序的灵活性。下面代码定义了CRectangle类,在该类中定义了一个setnum函数,并重载了setnum函数,代码如下:
#include<iostream>
using namespace std;
class CRectangle
{
private:
int m_Length;
int m_Width;
public:
CRectangle()
{
}
void setnum(int length)//setnum函数
{
cout << "我是length=" << length << endl;
}
void setnum(int length,int width)//重载setnum函数
{
cout << "我是length+width=" << length + width << endl;
}
~CRectangle()
{
}
};
int main()
{
CRectangle rect;
rect.setnum(10);
rect.setnum(10, 11);
return 0;
}
在上段代码中,编译器根据setnum函数的参数数量对两个setnum函数加以区分。运行结果如下:
(二)运算符重载:
重载的运算符是带有特殊名称的函数,函数名是由关键字 operator 和其后要重载的运算符符号构成的。与其他函数一样,重载运算符有一个返回类型和一个参数列表。
下面定义了一个CRectangle类,在该类中加载了运算符“++”,并使运算符“++”的步长为2,代码如下:
#include<iostream>
using namespace std;
class CRectangle
{
private:
int m_Length;
int m_Width;
public:
CRectangle()
{
m_Length = 10;
}
~CRectangle()
{
}
int operator++()
{
m_Length = m_Length + 2;
return m_Length;
}
};
int main()
{
CRectangle rect;
int i = 0;
i = ++rect;
cout << i << endl;
i = ++rect;
cout << i << endl;
return 0;
}
运行结果如图:
在C++语言中,并不是所有的运算符都能重载,不能重载的运算符见下图:
五:虚函数
在介绍虑函数之前要说一下多态性,多态性指的是一个接口具有多种功能。在C++语言中,有一种运行时的多态性,就是虚函数。虚函数的定义方法很简单,只要在基类中相应的方法定义原型前加上关键字就可以将该方法定义成虚函数了。
下面先定义一个基类CShape类,CShape类有一个派生类CCircIe类,然后通过CShape类
的对象来调用CCircIe类的方法,代码如下:
#include<iostream>
using namespace std;
class CShape
{
public:
CShape();
void output();
~CShape();
};
class CCircle : public CShape
{
public:
CCircle();
void output();
~CCircle();
};
CShape::CShape()
{
}
void CShape::output()
{
cout << "This is CShape" << endl;
}
CShape::~CShape()
{
}
CCircle::CCircle()
{
}
void CCircle::output()
{
cout << "This is CCircle" << endl;
}
CCircle::~CCircle()
{
}
int main()
{
CShape* pSha = new CCircle;
pSha->output();
delete pSha;
return