c++ - C++程序在Visual Studio 2010中编译,但不能在Mingw中编译

标签 c++ constructor casting operator-overloading template-classes

下面的程序在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;的操作,以防与答案相关。
我的问题是,如何使该语法按需工作?

最佳答案

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;
};
Demo

关于c++ - C++程序在Visual Studio 2010中编译,但不能在Mingw中编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64017554/

相关文章:

c++ - 传入一个 vector 作为具有设定值的参数

C++,帮助扩展这个类

c++ - 在此对象创建期间发生了哪些复制/分配操作?

c++ - 将对象指针转换为 char 数组

c - C 中的类型转换和类型安全

c++ - 如何使用 LuaBind 将 std::map 绑定(bind)到 Lua

c++ - 无法在没有初始化的情况下声明类?

聚合子类中的Java构造函数

objective-c - 在 cocoa 中进行类型转换以修复警告

c++ - 无法将纹理绑定(bind)到 GL_QUADS