c++ - 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(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
^
推荐阅读
- svg - SVG定义继承
- c# - MigraDoc 和 .NET Core 2.0
- wordpress - 模型页面模板未在后台 Wordpress 中激活
- postgresql - 关闭 docker-compose 后,Docker 卷不保留数据
- php - Wordpress - 使用 Guzzle 下载 GDrive 文件并在浏览器中显示正文响应
- jquery - 项目符号滑动切换外部 div
- javascript - 如何将数组的前一个字符串与下一个字符串连接起来?
- javascript - ExtJS:为嵌套对象设置默认面板项
- plot - 多边形不着色到 x 轴
- cocoa - 我可以得到另一个应用程序的 NSApplication 吗?