【问题标题】:C++ Linker Error involving operator overload function涉及运算符重载函数的 C++ 链接器错误
【发布时间】:2011-01-19 10:56:56
【问题描述】:

我有一个节点类型的列表。我想设置一个临时Node等于List前面的Node,如下:

class Node
{ 
   public:
      Node();
      Node& operator = (const Node& n);
};

但我不断收到链接器错误:

正在链接...
main.obj:错误 LNK2019:函数“void __cdecl fillScan( int,class std::list >)" (?fillScan@@YAXHV?$list@VNode@@V?$allocator@VNode@@@std@@@std@@@Z)
C:\Users\Aaron McKellar\Documents\School Stuff\CS445\Test\Debug\Test.exe : 致命错误 LNK1120: 1 unresolved externals

提前致谢!

【问题讨论】:

  • 感谢您的回复。我已经有一段时间没有完成运算符重载了。即使在浏览了我的书和在线之后,我仍然遇到问题。类节点{公共:节点();整数y;节点&运算符=(const Node& n); }; Node::Node() // 默认构造函数 { y = -1; } Node& Node::operator=(const Node& n) { if(this != n) { this.y = n.y; } 返回 *this;我不知道出了什么问题,但是当我这样做时,智能感知不会将其识别为 Node 对象。请帮忙,谢谢!
  • 1>正在编译... 1>main.cpp 1>c:\users\aaron mckellar\documents\school stuff\cs445\test\test\main.cpp(49):错误 C2679:二进制 '!=' : 没有找到采用 'const Node' 类型的右手操作数的运算符(或没有可接受的转换) 1> 可能是 'built-in C++ operator!=(Node *, Node *)' 1> c:\program files\microsoft sdks\windows\v6.0a\include\guiddef.h(197): 或 'int operator !=(const GUID &,const GUID &)' 1> 尝试匹配参数时list '(Node *const , const Node)'
  • 1>c:\users\aaron mckellar\documents\school stuff\cs445\test\test\main.cpp(51):错误 C2228:'.y' 左侧必须有类/结构/union 1> type is 'Node *const ' 1> 你打算用 '->' 代替吗?
  • 我也试过 return this = n;但我得到了这个: 1>c:\users\aaron mckellar\documents\school stuff\cs445\test\test\main.cpp(56) : error C2440: '=' : cannot convert from 'const Node' to 'Node *const ' 1> 没有可以执行此转换的用户定义转换运算符,或者无法调用该运算符

标签: c++ list operator-overloading linker-errors


【解决方案1】:

您只显示了operator= 的声明,而不是定义。要么您没有提供定义,要么链接器找不到它。

好吧,我应该说:链接器肯定找不到operator= 的定义。要么是因为您忘记提供一个,要么是因为您的项目/Makefile 设置不正确。

【讨论】:

  • 请在上方查看我的 cmets
【解决方案2】:

您当然需要为operator= 提供定义:

Node& Node::operator=(const Node& n) {

     // 'copy' semantics for Node
}

请注意,如果没有提供,编译器会使用成员复制自己生成赋值运算符。如果足够,请使用编译器生成的运算符。

【讨论】:

  • 请在上方查看我的 cmets
猜你喜欢
  • 2011-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-03
  • 1970-01-01
  • 2015-07-04
  • 1970-01-01
  • 2020-12-28
相关资源
最近更新 更多