gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:58:26 25 4
gpt4 key购买 nike

下面的程序在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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com