C++类的默认成员函数

C++类有六个默认的成员函数,分别是构造函数、析构函数、拷贝构造函数、赋值运算符重载函数、&运算符重载函数、const &运算符重载函数。

下面分别说明:

定义一个class CTestClass{};类。

1、构造函数

类实例化时执行的函数。

CTestClass();

2、析构函数

类释放时执行的函数。

~CTestClass();

3、拷贝构造函数

CTestClass(const CTestClass& cls);

默认的拷贝构造函数执行的是浅拷贝,即对成员变量直接按值拷贝(若成员变量不存在指针或申请动态内存的情况下深浅拷贝没有区别)。拷贝构造函数传递参数为const是为了防止函数参数传值时复制拷贝(执行拷贝构造函数),因为本身已经是拷贝构造函数,若传递参数再执行拷贝构造函数则会陷入死循环。

4、赋值运算符重载函数

CTestClassExt& operator=(const CTestClassExt& cls);

5、&运算符重载函数

CTestClassExt* operator&();

6、const &运算符重载函数

const CTestClassExt* operator&()const;


测试代码:

定义了两个类,CTestClass和CTestClassExt。CTestClassExt对默认的成员函数做了修改。

CTestClass定义:

class CTestClass  
{
public:
CTestClass();
~CTestClass();


public:
int m_iValue;


};

CTestClass::CTestClass()
{


}


CTestClass::~CTestClass()
{


}

CTestClassExt定义:

class CTestClassExt  
{
public:
CTestClassExt();
CTestClassExt(const CTestClassExt& cls);
virtual ~CTestClassExt();


CTestClassExt& operator =(const CTestClassExt& cls)
{
m_iValue = cls.m_iValue + 2;


return *this;
}


CTestClassExt* operator&() 
{
m_iValue+=3;


return this;
}


const CTestClassExt* operator&()const 
{
//m_iValue+=4;//const函数无法修改成员变量的值


return this;
}


public:
int m_iValue;


};

CTestClassExt::CTestClassExt()
{
m_iValue = 10;
}


CTestClassExt::CTestClassExt(const CTestClassExt& cls)
{
m_iValue = cls.m_iValue + 1;
}


CTestClassExt::~CTestClassExt()
{


}

main函数测试代码:

int main(int argc, char* argv[])
{
CTestClassExt cls_ext;
CTestClass cls;


printf("cls.m_iValue = %d\r\n", cls.m_iValue);//未初始化的值
printf("cls_ext.m_iValue = %d\r\n", cls_ext.m_iValue);//构造函数中初始化


cls.m_iValue = 0;
CTestClassExt cls_ext2(cls_ext);//拷贝构造函数
printf("cls_ext.m_iValue = %d\r\n", cls_ext.m_iValue);//构造函数中初始化
printf("cls_ext2.m_iValue = %d\r\n", cls_ext2.m_iValue);//通过拷贝构造函数初始化,拷贝构造函数中对值+1


CTestClassExt cls_ext3 = cls_ext;//这种风格执行拷贝构造函数
printf("cls_ext.m_iValue = %d\r\n", cls_ext.m_iValue);//构造函数中初始化
printf("cls_ext3.m_iValue = %d\r\n", cls_ext3.m_iValue);


cls_ext3 = cls_ext;//通过=号操作符初始化
printf("cls_ext.m_iValue = %d\r\n", cls_ext.m_iValue);//构造函数中初始化
printf("cls_ext3.m_iValue = %d\r\n", cls_ext3.m_iValue);//通过=号操作符初始化,拷贝构造函数中对值+2


//&
printf("&cls_ext = %d\r\n", &cls_ext);
printf("cls_ext.m_iValue = %d\r\n", cls_ext.m_iValue);//&的左值运算+3


cls_ext.m_iValue = 10;
//const &由于默认的函数定义为const函数,因此不能修改变量,无法测试验证。


return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值