[英]Using MinGW built dll in a Visual Studio 2010 C++ project
[英]C++ program compiles in Visual Studio 2010 but not Mingw
下面的程序可以在 VS 2010 中編譯,但不能在最新版本的 Mingw 中編譯。 Mingw 給我錯誤“請求從 int 轉換為非標量類型‘tempClass(it)’”。 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
}
評論/評論賦值運算符部分似乎沒有什么不同——我沒想到,我只是把它包括在內,因為我也希望做像tempClass <it> a = 5; a = 6;
這樣的事情。 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;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.