【发布时间】:2021-01-09 00:58:53
【问题描述】:
下面的程序在 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;之类的事情,以防这与答案。
我的问题是,我怎样才能让这种语法按需要工作?
【问题讨论】:
-
不相关,但您为什么使用已有十年历史的工具?过去 10 年发生了很多事情,无论是 C++ 标准还是您的工具标准合规性。
-
MinGW 基本上已经过时了,因为Windows Subsystem for Linux 提供了更好的体验。它也有现代编译器。一个有 10 年历史的 C++ 编译器实际上是垃圾。
-
我刚刚有一台计算机,不久前已经安装了 C++ 编译器。我只安装了 Mingw,因为我想使用可变参数模板。无论哪种方式,我怎样才能让这个语法工作?
-
@tadman MinGW 及其衍生产品的存在理由是使用 gcc 构建使用 Windows API 的代码,因此 WSL 不会淘汰它
-
@M.M 如果你更喜欢 Visual Studio,那么我猜你会被淘汰。我看到很多人都在为 MinGW 苦苦挣扎,他们只是在尝试编译,暂时没有考虑特定的目标。
标签: c++ constructor casting operator-overloading template-classes