1.构造函数、复制构造函数、析构函数
先上例子好了:
#include "stdafx.h"
#include<iostream>
using namespace std;
class CRectangle
{
public:
CRectangle();//构造函数
~CRectangle();//析构函数
CRectangle(int length,int width);//自定义的构造函数
CRectangle(const CRectangle& theRectangle)//复制构造函数
{
m_length = theRectangle.m_length;
m_width = theRectangle.m_width;
printf("copyConstructor~\n");
}
private:
int m_length;
int m_width;
int area();
};
CRectangle::CRectangle()//构造函数
{
printf("constructor~\n");
}
CRectangle::~CRectangle()//析构函数
{
printf("disconstruct~\n");
}
int CRectangle::area()
{
return m_length*m_width;
}
CRectangle::CRectangle(int length, int width)//自定义的构造函数
{
m_length = length;
m_width = width;
printf("secConstructor\n");
}
int _tmain(int argc, _TCHAR* argv[])
{
CRectangle rect1;
CRectangle rect2(10, 12);
CRectangle rect3(rect2);
//system("pause");
return 0;
}
程序运行截图如下:
构造函数:是一个与类名同名的方法,可以根据需要设置参数,但是不具有返回值。在声明类时,如果没有提供构造函数,编译器会提供一个默认的构造函数,默认构造函数没有参数也不进行任何操作。一个类可以有多个构造函数,但是每个构造函数必须在形参数量和类型上有所不同。由此编译器区分不同的构造函数。
复制构造函数:只有一个参数,即该类对象的引用。在以下情况下会使用复制构造函数:
- 用一个已存在的类对象初始化同一个类的新对象时;
- 把一个类对象的副本作为参数传递给参数时;
- 返回值为一个类对象时
析构函数:在对象被撤销后清除并释放所分配的内存。析构函数没有返回值和参数。如果对象是在栈中被创建的,那么在对象失去作用域时,系统会自动调用其析构函数来释放对象占用的内存。
上面的实例执行后,会显示调用了一次构造函数、带参数的构造函数、复制构造函数以及三次析构函数。由此体现,复制构造函数也是构造函数呐。
2.方法的重载和运算符的重载
方法的重载应该是带参数的构造函数的普通函数版。在同一个类(注意是同一个类,如果是继承里面就叫做多态。)中,多个方法共用一个名称,彼此间一参数的类型和参数的个数互相区别。
运算符的重载,个人觉得挺新鲜的,其格式为:返回值类型 operator 运算符(参数列表)。./.*/::/?.这四个运算符是不能重载的。
在上述代码的类定义中增加如下声明:对++运算符进行重载
int operator ++(){
m_length = m_length + 2;
return m_length;
}
main函数中对++运算符进行引用: int i = ++rect2;
cout << i << endl;
最后会输出12.说明重载成功。2.虚函数、纯虚函数
虚函数:其作用是,在调用一个虚函数时,是以对象运行时的类型确定的,而不是以对象声明时的类型为准。定义方法为:在基类中相应的方法定义原型前加上关键字virtual就可以了。
纯虚函数:在基类中只有声明没有实现。含有纯虚函数的类被称为抽象类。用户只能从抽象类中派生子类而不能声明抽象类对象。如果子类派生与一个抽象类,那么子类必须实现抽象类中所有纯虚函数。定义方法为:在基类中相应的方法定义原型前加上关键字virtual,在函数结束的末尾添加"=0"。
运行一个例子好了:
#include "stdafx.h"
#include<iostream>
using namespace std;
class shape
{
public:
shape();
~shape();
virtual void output();
private:
};
shape::shape()
{
}
shape::~shape()
{
}
void shape::output(){
cout << "this is shape" << endl;
}
class rectangle:public shape
{
public:
rectangle();
~rectangle();
void output();
private:
};
rectangle::rectangle()
{
}
void rectangle::output(){
cout << "this is rectangle" << endl;
}
rectangle::~rectangle()
{
}
int _tmain(int argc, _TCHAR* argv[])
{
shape *s1 = new rectangle;
s1->output();
delete s1;
system("pause");
return 0;
}
输出的是“this is rectangle”3.this指针
每个方法都有一个this指针。this指针用于指向以该方法所属类定义的对象。当对象调用方法时,方法的this指针就指向该对象。在不同对象调用同一方法时,编译器将根据this指针所指的不同对象来确定应该引用哪一个对象的数据成员。