类中隐式类型转换

1.隐式类型转换

C++中定义了内置类型的几个自动转换,为了定义到类类型的隐式转换,必须定义合适的构造函数。

        可以用单个实参来调用的构造函数定义了从形参类型到该类类型的隐式转换。

来看一下例子:

#include <iostream>
#include <stdio.h>
using namespace std;
#include  <iostream>


using namespace std;


class Base
{
private:
    int data;
public:
    Base(){ cout << "defalut constructor \n" << endl;}


     // this is a destructor:


    ~Base(){ cout<<"destructed" << endl;}
    Base(int i):data(i)
    {
        cout << "constructed by parameter " << data << endl;
    }
};


Base play( Base b)
{
    return b;
}


int main()
{
       Base temp = play(5);
       return 0;
}

打印输出一下:


可以看到在需要一个Base类型的参数,传入 int类型,会自动调用 隐式转换。生成一个 Base对象,该对象 在局部函数完毕后就 自动析构,如果想抑制这种隐式转换,需要在前面加一个explicit 参数。

explicit关键字  只能用在类内部的构造函数声明中,不能加在定义的前面。

总结:单个参数的构造函数不添加explicit参数的时候,会定义一个从隐式转换,从参数的类型到自己的类类型。添加explicit就会消除这种隐患。

添加了之后可以显式的使用构造函数来构造。下面这样。

#include <iostream>
#include <stdio.h>
using namespace std;
#include  <iostream>

using namespace std;

class Base
{
private:
    int data;
public:
    Base(){ cout << "defalut constructor \n" << endl;}

     // this is a destructor:

    ~Base(){ cout<<"destructed" << endl;}
    explicit Base(int i):data(i)
    {
        cout << "constructed by parameter " << data << endl;
    }
};

Base play( Base b)
{
    return b;
}

int main()
{
       Base temp = play(Base(5));
       return 0;
}




2.构造函数默认实参

      默认实参的作用是减少代码重复。看下面的构造函数
    
#include <iostream>
#include <stdio.h>
#include <string.h>


using namespace std;

class MyString
{
private:
    char *m_data;
public:
    //普通构造函数
    MyString(const char * str  = NULL);
}
MyString::MyString(const char *str)
{
    cout << "constructing  string by " << str << endl;
    if(str == NULL)
    {
        m_data = new char[1];
        *m_data = '\0';
    }
    else
    {
        int len = strlen(str);
        m_data = new char[len + 1];
        strcpy(m_data,str);
    }
}
int main()
{
    MyString s;


}
加上一个默认实参,可以 直接 定义  没有参数的 s   ,默认实参只能出现在 声明中,不能出现在定义中。如
MyString::MyString(const char *str = NULL)

就是错误的。


   


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值