繁体   English   中英

C++ 程序在 Visual Studio 2010 中编译但不在 Mingw 中编译

[英]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 拒绝代码是正确的,因为它依赖于两个隐式用户定义的转换。 一个从intit ,一个从ittempClass<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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM