[英]C++ program compiles in Visual Studio 2010 but not Mingw
The program below compiles in VS 2010, but not in a recent version of Mingw.下面的程序可以在 VS 2010 中编译,但不能在最新版本的 Mingw 中编译。 Mingw gives me the error "conversion from int to non-scalar type 'tempClass(it)' requested".
Mingw 给我错误“请求从 int 转换为非标量类型‘tempClass(it)’”。 Class "it" is just a simple class to use in the template for the purpose of illustration.
Class “它”只是一个简单的 class,用于模板中用于说明目的。
#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
}
Commenting in/out the assignment operator portion doesn't seem to make a difference - I didn't expect it to, I just included it because I also hope to do things like tempClass <it> a = 5; a = 6;
评论/评论赋值运算符部分似乎没有什么不同——我没想到,我只是把它包括在内,因为我也希望做像
tempClass <it> a = 5; a = 6;
这样的事情。 tempClass <it> a = 5; a = 6;
, in case this is relevant to the answer. ,以防这与答案相关。
My question is, how can I get this syntax to work as desired?我的问题是,我怎样才能让这个语法按预期工作?
MinGW is correct to refuse the code since it relies on two implicit user-defined conversions. MinGW 拒绝代码是正确的,因为它依赖于两个隐式用户定义的转换。 One from
int
to it
and one from it
to tempClass<it>
.一个从
int
到it
,一个从it
到tempClass<it>
。 Only one user-defined implicit conversion is allowed.只允许一种用户定义的隐式转换。
The below works since it only requires one implicit conversion:下面的工作因为它只需要一个隐式转换:
tempClass<it> thisOne = it(5);
You can also let the constructor do the conversion which will let you do您还可以让构造函数进行转换,这会让您这样做
tempClass<it> thisOne = 5;
. . In the below example the constructor will accept any argument and will try to initialize
theVar
with it.在下面的示例中,构造函数将接受任何参数并尝试用它初始化
theVar
。 If U
is convertible to T
, it'll compile and work as expected.如果
U
可转换为T
,它将按预期编译和工作。 Otherwise you'll get a compilation error about an invalid conversion.否则,您将收到有关无效转换的编译错误。
template<class T>
class tempClass {
public:
template<typename U>
tempClass(U a) : theVar(a) {}
//private:
T theVar;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.