在InsertFlight方法中遭遇Visual Studio错误C2665,寻求修复方案
修复Visual Studio错误代码C2665:InsertFlight方法问题
原本打算发布完整代码,但受网站格式限制只贴出了相关结构体代码,InsertFlight是某个类的成员方法。目前在调用InsertFlight时触发Visual Studio错误C2665,相关代码如下:
struct FlightRec { string FlightNO; string Destination; TimeRec Time; FlightType Ftype; bool Delay; TimeRec ExpectedTime; // if the flight is delayed }; template <class T> struct Node { T entry; Node<T>* next; }; // Add a flight to the list void InsertFlight(const T& flight) { // Create a new node for the flight Node<T>* node = new Node<T>(flight); // Add the node to the head of the list node->next = head; head = node; }
错误原因
C2665错误本质是找不到匹配的函数重载。这里问题出在new Node<T>(flight)这一行:你定义的Node<T>结构体没有提供接收const T&参数的构造函数,编译器无法自动生成合适的构造逻辑来用传入的flight初始化节点的entry成员。
修复方案
方案一:给Node结构体添加构造函数
修改Node<T>结构体,显式定义构造函数来初始化entry和next:
template <class T> struct Node { T entry; Node<T>* next; // 添加构造函数 Node(const T& val) : entry(val), next(nullptr) {} };
这样new Node<T>(flight)就能正常调用构造函数,完成节点初始化。
方案二:手动初始化节点成员
如果不想修改Node结构体,可以先创建空节点,再手动赋值entry:
void InsertFlight(const T& flight) { Node<T>* node = new Node<T>(); // 创建空节点 node->entry = flight; // 手动赋值entry node->next = head; head = node; }
注意:这种方式要求T类型(比如FlightRec)支持赋值操作,你的FlightRec包含string等类型,默认赋值是没问题的。
内容的提问来源于stack exchange,提问作者Kunel Jo
相关产品推荐
相关产品推荐

