【问题标题】:C++ program compiles in Visual Studio 2010 but not MingwC++ 程序在 Visual Studio 2010 中编译但不是 Mingw
【发布时间】: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 &lt;it&gt; 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


【解决方案1】:

MinGW 拒绝代码是正确的,因为它依赖于 两个 隐式用户定义的转换。一个从intit,一个从ittempClass&lt;it&gt;。只允许一个用户定义的隐式转换。

因为它只需要一个隐式转换,所以下面的工作:

tempClass<it> thisOne = it(5);

您也可以让构造函数进行转换,您可以这样做
tempClass&lt;it&gt; thisOne = 5;。在下面的示例中,构造函数将接受 any 参数并尝试使用它初始化 theVar。如果U 可转换为T,它将按预期编译和工作。否则,您将收到有关无效转换的编译错误。

template<class T>
class tempClass {
public:
    template<typename U>
    tempClass(U a) : theVar(a) {}

//private:
    T theVar;
};

Demo

【讨论】:

  • 我想我没有发布实际的问题,即如何才能使该语法起作用?
  • @HumidMorning 通过在tempClass 中添加转换构造函数模板。我添加了它作为示例,现在也添加了一个小演示。
猜你喜欢
  • 1970-01-01
  • 2011-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多