c ++显式构造函数未阻止从double到int的转换

问题描述 投票:1回答:2

我有一个从int构造C的构造函数,从double构造一个C的构造函数。

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

但是很不幸,出现了从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
2个回答
0
投票

嗯! Eljay在注释中得到的速度更快,但这是最终代码,试图隐式使用double会导致编译错误

#include <iostream>
using namespace std;

class C{
    int* tab;

public:
    //THE TRICK: block any implicit conversion by default
    template <class T> C(T) = delete;

    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 other types deleted
        C o5 = (C)5.0; //ok. explicit conversion
    }
    cout << "stop\n";
}

0
投票

您可以尝试使用例如启用类型特征的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
                ^
© www.soinside.com 2019 - 2024. All rights reserved.