构造函数不仅可以构造与初始化对象,对于单个参数或者除第一个参数无默认值其余均有默认值的构造函数,还具有类型转换的作用。

  1. 单参构造函数,没有使用explicit修饰,具有类型转换作用 explicit修饰构造函数,禁止类型转换---explicit去掉之后,代码可以通过编译。
  2. 虽然有多个参数,但是创建对象时后两个参数可以不传递,没有使用explicit修饰,具有类型转换作用。
 class Date
{
public:
 explicit Date(int year)
 :_year(year)
 {}
 // explicit修饰构造函数,禁止类型转换
 explicit Date(int year, int month = 1, int day = 1)
 : _year(year)
 , _month(month)
 , _day(day)
 {}
 */
 Date& operator=(const Date& d)
 {
 if (this != &d)
 {
 _year = d._year;
 _month = d._month;
 _day = d._day;
 }
 return *this;
 }
private:
 int _year;
 int _month;
 int _day;
};
void Test()
{
 Date d1(2022);
 // 用一个整形变量给日期类型对象赋值
 // 实际编译器背后会用2023构造一个无名对象,最后用无名对象给d1对象进行赋值
 d1 = 2023;
 // 将1屏蔽掉,2放开时则编译失败,因为explicit修饰构造函数,禁止了单参构造函数类型转
换的作用
}
// 单参数的构造函数
class A
{
public:
    explicit A(int a)
        :_a1(a)
    {
        cout << "A(int a)" << endl;
    }

    //explicit A(int a1, int a2)
    A(int a1, int a2)
        :_a1(a1)
        , _a2(a2)
    {}

    A(const A& aa)
        :_a1(aa._a1)
    {
        cout << "A(const A& aa)" << endl;
    }

private:
    int _a2;
    int _a1;
};

int main()
{
    // 单参数构造函数 C++98
    A aa1(1);  // 构造函数
    //A aa2 = 1; // 隐式类型转换   构造+拷贝+优化->构造
    //const A& ref = 10;


    // 多参数构造函数 C++11
    A aa2(1, 1);
    A aa3 = { 2, 2 };
    const A &ref = { 2, 2 };

    int i = 1;
    double d = i; // 隐式类型转换

    return 0;
}
上述代码可读性不是很好,explicit修饰构造函数,将会禁止构造函数的隐式转换

Hhh_灏
24 声望3 粉丝