类的六个默认成员函数:构造函数、拷贝构造函数、析构函数、赋值操作符重载、取地址的操作符重载、const修饰的取地址操作符重载。

1.【构造函数】
成员变量为私有的,要对它们进行初始化,必须用一个公有成员函数来进行。同时这个函数应该有且仅在定义对象时自动执行一次,这时
调用的函数称为构造函数(constructor) 。
构造函数是特殊的成员函数,其特征如下:
1. 函数名与类名相同。
2. 无返回值。
3. 对象构造(对象实例化)时系统自动调用对应的构造函数。
4. 构造函数可以重载。
5. 构造函数可以在类中定义,也可以在类外定义。
6. 如果类定义中没有给出构造函数,则C++编译器自动产生一个缺省的构造函数,但只要我们定义了一个构造函数,系统就不会自动
生成缺省的构造函数。
7. 无参的构造函数和全缺省值的构造函数都认为是缺省构造函数,并且缺省的构造函数只能有一个。
class Date
{
public:
// 1.无参构造函数
Date ()
{}
// 2.带参构造函数
Date (int year, int month , int day )
{
_year = year ;
_month = month ;
_day = day ;
}
private:
int _year ;
int _month ;
int _day ;
};
void TestDate1 ()
{
Date d1 ; // 调用无参构造函数
Date d2 (2015, 1, 1); // 调用带参的构造函数
}2.【拷贝构造函数】
创建对象时使用同类对象来进行初始化,这时所用的构造函数称为拷贝构造函数(Copy Constructor),拷贝构造函数是特殊的构造函
数。
特征:
1. 拷贝构造函数其实是一个构造函数的重载。
2. 拷贝构造函数的参数必须使用引用传参,使用传值方式会引发无穷递归调用。
3. 若未显示定义,系统会默认缺省的拷贝构造函数。缺省的拷贝构造函数会,依次拷贝类成员进行初始化。
class Date
{
public :
Date()
{}
// 拷贝构造函数
Date (const Date& d)
{
_year = d ._year;
_month = d ._month;
_day = d ._day;
}
private :
int _year ;
int _month ;
int _day ;
};
void TestDate1 ()
{
Date d1
Date d2 (d1); // 调用拷贝构造函数
}3.【析构函数】
当一个对象的生命周期结束时,C++编译系统会自动调用一个成员函数,这个特殊的成员函数即析构函数(destructor)
构造函数是特殊的成员函数,其特征如下:
1. 析构函数在类名加上字符~。
2. 析构函数无参数无返回值。
3. 一个类有且只有一个析构函数。若未显示定义,系统会自动生成缺省的析构函数。
4. 对象生命周期结束时,C++编译系统系统自动调用析构函数。
5. 注意析构函数体内并不是删除对象,而是做一些清理工作。
class Date
{
public :
// 析构函数
~Date()
{}
private :
int _year ;
int _month ;
int _day ;
};4.【赋值运算符重载】
1、拷贝构造函数是创建的对象,使用一个已有对象来初始化这个准备创建的对象。
2、赋值运算符的重载是对一个已存在的对象进行拷贝赋值。
class Date
{
public :
Date()
{}
// 拷贝构造函数
Date (const Date& d)
: _year(d._year)
, _month(d._month)
, _day(d._day)
{}
// 赋值操作符的重载
Date& operator = (const Date& d)
{
if (this != &d)
{
this->_year = d. _year;
this->_month = d. _month;
this->_day = d. _day;
}
return *this ;
}
private:
int _year ;
int _month ;
int _day ;
};
void Test ()
{
Date d1 ;
Date d2 = d1; // 调用拷贝构造函数
Date d3 ;
d3 = d1 ; // 调用赋值运算符的重载
}操作符重载实现的加减乘除
Date operator= (const Date &g)
{
if (this != &g)
{
_year=g._year;
_month=g._month;
_day=g._day;
}
return *this;
}
Date operator+ (const Date g)
{
Date d;
d._year = _year + g._year;
d._month = _month + g._month;
d._day = _day + g._day;
return d;
}
Date operator+= (const Date g)
{
_year += g._year;
_month += g._month;
_day += g._day;
return *this;
}
Date operator-(const Date g)
{
Date d;
d._year=_year-g._year;
d._month=_month-g._month;
d._day=_day-g._day;
return d;
}在C++中比较常用的就是以上四个默认成员函数,我们在熟悉了以上四个默认函数的特点和用法之后,我们可以练习实现一个复数类。
class Complex
{
public:
Complex()
{}//无参构造函数
Complex(int real,int empty)
{
_real=real;
_empty=empty;
}//带参构造函数
Complex (const Complex& g)
{
_real=g._real;
_empty=g._empty;
}//拷贝构造函数
void Display()
{
cout<<"real:"<< _real<<"empty:"<< _empty<
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
本文标题:类的默认成员函数-创新互联
转载注明:http://www.scyingshan.cn/article/dcepoi.html


咨询
建站咨询
