gpt4 book ai didi

c++ - C++显式构造函数不阻止将double转换为int

转载 作者:行者123 更新时间:2023-12-02 10:20:58 25 4
gpt4 key购买 nike

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

我让第一个执行隐式类型转换,但是使用关键字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

最佳答案

好! 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";
}

关于c++ - C++显式构造函数不阻止将double转换为int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60193654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com