首页 > 解决方案 > c ++显式构造函数不阻止double到int的转换

问题描述

我有一个来自 int 的 C 类的构造函数和一个来自 double 的构造函数。

我让第一个进行隐式类型转换,但使用关键字显式阻止第二个。

但是,不幸的是,出现了一个 double 到 int 的隐式转换。我可以以某种方式阻止它吗?

这是一个简化的例子

//g++  5.4.0
#include <iostream>
using namespace std;

class C{
    int* tab;
    public:
    C():tab(nullptr){ cout<<"(void)create zilch\n"; }
    C(int size):tab(new int[size]){ cout<<"(int)create " << size << "\n"; }
    explicit C(double size):tab(new int[(int)size]){ cout<<"(double)create " << size << "\n"; }
    ~C(){ if(tab) {cout<<"destroy\n"; delete[] tab;} else cout <<"destroy zilch\n"; }
};    

int main()
{
    cout << "start\n";
    {
        C o1(1);
        C o2 = 2; //ok, implicit conversion allowed
        C o3(3.0);
        C o4 = 4.0; //ko, implicit conversion to double blocked... but goes to int 
    }
    cout << "stop\n";
}

//trace 
//
//start
//(int)create 1
//(int)create 2
//(double)create 3
//(int)create 4
//destroy
//destroy
//destroy
//destroy
//stop

标签: c++explicit

解决方案


您可以尝试将 C(int) 构造函数替换为使用启用类型特征的构造函数,例如

#include <iostream>
#include <type_traits>
using namespace std;

class C{
    int* tab;
    public:
    C():tab(nullptr){ cout<<"(void)create zilch\n"; }
    template<typename I, typename = typename enable_if<is_integral<I>::value>::type>
    C(I size):tab(new int[size]){ cout<<"(int)create " << size << "\n"; }
    explicit C(double size):tab(new int[(int)size]){ cout<<"(double)create " << size << "\n"; }
    ~C(){ if(tab) {cout<<"destroy\n"; delete[] tab;} else cout <<"destroy zilch\n"; }
};

int main()
{
    cout << "start\n";
    {
        C o1(1);
        C o2 = 2; //ok, implicit conversion allowed
        C o3(3.0);
        C o4 = 4.0; //ko, implicit conversion to double blocked... but goes to int
    }
    cout << "stop\n";
}

这会给你一个像这样的错误:

test.cpp: In function ‘int main()’:
test.cpp:22:16: error: conversion from ‘double’ to non-scalar type ‘C’ requested
         C o4 = 4.0; //ko, implicit conversion to double blocked... but goes to int
                ^

推荐阅读