我当时正在上一门课:
#include <iostream>
#include <list>
using namespace std;
class Int{
list <int64_t> data;
bool sign;
public:
Int(int64_t val = 0) : sign(false) {
cout << "Int(int) called\n";
}
Int(const char* str): sign(false) {
cout << "Int(const char* called)\n";
}
};
int main(){
Int a = "328739"; // line 1, ok
Int a2 = "ehfjhs"; // line 2, ok
Int a3 = 4338974; // line 3, ok
Int a4 = 0; //line 4, Issue
return 0;
}除了第4行之外,一切都很正常。
只要我执行Int a4 = 0;,构造函数Int(const char* str)就会被调用,因为0等同于NULL。但我希望调用的是Int(int64_t val = 0)。
我可以做的一个简单的修复方法是做Int a4 = int(0);,这在某一方面是可以的。但我想让它更灵活,所以0只触发Int(int64_t val = 0)。
发布于 2021-05-27 15:16:59
作为另一个答案的替代方案,您可以创建一个接受任何整型的模板构造函数。这将解决多义性,并额外适用于任何整型或文字。
#include <iostream>
#include <list>
using namespace std;
class Int{
list <int64_t> data;
bool sign;
public:
template <typename T, std::enable_if_t<std::is_integral_v<T>>* = nullptr>
Int(T val = 0) : sign(false) {
cout << "Int(Integral) called\n";
}
Int(const char* str): sign(false) {
cout << "Int(const char* called)\n";
}
};
int main(){
Int a = "328739"; // line 1, ok
Int a2 = "ehfjhs"; // line 2, ok
Int a3 = 4338974; // line 3, ok
Int a4 = 0; // line 4, ok
return 0;
}https://stackoverflow.com/questions/67716395
复制相似问题