lesson3-3构造函数精讲

构造函数

构造函数为特殊的成员函数,一般为piblic,若为private则无法新建对象,自动被调用,确定可以被正确初始化,但凡写了一个构造函数便不能生成默认构造函数。
首先,以classdemo为例,右键添加类,双击c++类新建名字回车,出现.h和.cpp两个文件
如下图所示:

.h如下:
#pragma once
class Classdemo2
{
public:
    Classdemo2(void);
    ~Classdemo2(void);
};
.cpp如下:
#include "Classdemo2.h"
Classdemo2::Classdemo2(void)
{
}
Classdemo2::~Classdemo2(void)
{
}
其中#progma once是防止头文件被多层包含,主要在windons下使用,在.h中更改如下:
#ifndef _CLASSDEMO2_H_
#define _CLASSDEMO2_H_
... ...
#endif//!_CLASSDEMO2_H_
以上为预包含方式

结束之后,我们将main.cpp中包含一个头文件
#include“Classdemo.h”便可实现类的创建和使用。

此外,C++中的namespace机制的使用如下:

命名空间

namespace PoEdu
{
class Classdemo2
{
public:
    Classdemo2(void);
    ~Classdemo2(void);
};
}
在Classdemo.cpp中加上 using namespace PoEdu;

命名污染

#include"string.h"  //首先从本地目录找
#include<string>//首先从系统工程目录寻找
using namespace std;
using namespace PoEdu;//PoEdu包含string类
string.str;//此时会出现错误,命名污染,分不清string是哪个命名空间的

如何调用及传参

Classdemo2(int num);
private:int GetNum();//在.h中
Classdemo2::Classdemo2(int num)
{
   cout<<"Classemo2("<<num<<")"<<endl;
   _num=num;
}
int Classdemo2::GetNum()
{ 
   return _num;
}                     //在.cpp中写

Classdemo2 demo;                         //调用构造
Classdemo2 demo1(10);                    //调用析构
std::cout<<demo.GetNum()<<std::endl;     //未定义的值
std::cout<<demo1.GetNum()<<std::endl;    //10

其他调用方式

Classdemo2*demo=new Classdemo2;
Classdemo2*demo=new Classdemo2(10);//传值
delete demo;//调用析构
Classdemo2 array[10];//调用无参10次
Classdemo2 array[10]={1};//调用1次有参 9次无参
Classdemo2*demo=new Classdemo2[10];//无参10次
Classdemo2 *demo=static_cast<Classdemo2*>(malloc(sizeof(Classdemo2)));
free(demo);//malloc不会调用构造函数

转换构造函数

Classdemo2 demo=10等价于Classdemo2 demo(10//此时的=会调用构造函数而不是赋值
Classdemo2(int num);//刚好传递进1参  能构成转换构造函数

demo=20;//赋值函数
发生如下步骤:新建临时对象-将临时对象传给demo-析构了临时对象
同时会默认生成赋值运算符:
Classdemo2&operator=(const Classdemo2&other)
在.cpp中书写如下:
Classdemo2& Classdemo2::operator=(const Classdemo2&other)//括号内是临时对象
{
    _num=other._num;
    cout<<"operator("<<_num<<")"<<endl;
    return *this;
}

运行结果如图

{
    Classdemo2 temp=20;
    demo.operator=(temp);//先生成临时对象temp,将temp赋值给demo的operator,函数内部则是相应值的传递
}

operator=的重载

Classdemo2&operator=(const Classdemo2& other);
Classdemo2&operator=(const int& other)
{
    _num=other;
    cout<<"operator(int="<<_num<<")"<<endl;
    return *this;
}//这两者构成重载

在主函数输入如下代码:

Classdemo2 demo=10;     //转换构造
demo=20;                //赋值,调用第2个operator
{
    Classdemo2 demo2=30;
    demo=demo2;
}                     //转换构造——赋值(第1个operator)--析构掉demo2
std::cout<<demo.GetNum()<<std::endl;

结果如下图所示:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值