下面的程序在VS 2010中编译,但在Mingw的最新版本中未编译。 Mingw给我一个错误“请求从int转换为非标量类型'tempClass(it)'”。类“it”只是用于说明目的而在模板中使用的简单类。
#include <iostream>
#include <string>
using namespace std;
template <class T>
class tempClass{
public:
T theVar;
tempClass(){}
tempClass(T a){
theVar = a;
}
/* tempClass <T> & operator = (T a){
(*this) = tempClass(a);
return *this;
}
*/
};
class it{
public:
int n;
it(){}
it(int a){
n = a;
}
};
int main(){
tempClass <it> thisOne = 5; // in MinGW gives error "conversion from int to non-scalar type 'tempClass(it)' requested"
cout << thisOne.theVar.n << endl; // in VS 2010 outputs 5 as expected
}
注释掉赋值运算符部分似乎没有什么不同-我没想到会这样,我只是将其包括在内,因为我还希望做类似tempClass <it> a = 5; a = 6;
的操作,以防与答案相关。我的问题是,如何使该语法按需工作?
最佳答案
MinGW拒绝代码是正确的,因为它依赖于两个隐式的用户定义的转换。一种是从int
到it
,另一种是从it
到tempClass<it>
。只允许一个用户定义的隐式转换。
下面的方法起作用,因为它只需要一次隐式转换:
tempClass<it> thisOne = it(5);
您还可以让构造函数进行转换,这将使您能够tempClass<it> thisOne = 5;
。在下面的示例中,构造函数将接受任何参数,并尝试使用该参数初始化theVar
。如果U
可转换为T
,它将编译并按预期工作。否则,您将收到有关无效转换的编译错误。template<class T>
class tempClass {
public:
template<typename U>
tempClass(U a) : theVar(a) {}
//private:
T theVar;
};
Demo
关于c++ - C++程序在Visual Studio 2010中编译,但不能在Mingw中编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64017554/