我正在为要重载“>>”运算符的类进行 C++ 赋值。我在 Visual Studio 2005 和 Xcode 3.2.2 中都遇到了链接错误。 C++代码被分成几个文件。原型(prototype)存储在 overload.h 中,实现存储在 overload.cpp 中,main()
在 overloadtester.cpp 中(尽管我还没有能够将与这个新的重载运算符相关的任何内容放入主要是因为错误。下面是我在开始收到错误之前添加的代码(下面列出)
// overload.h
// Class Name OverloadClass
#ifndef _OverloadClass_H
#define _OverloadClass_H
#include < string >
using namespace std ;
class OverloadClass
{
public:
// Constructors and methods
private:
x_;
y_;
};
istream& operator>> (istream& in, OverloadClass &p);
#endif
// overload.cpp
#include < iostream >
#include < string >
#include < sstream >
#include < istream >
extern "C"
{
#include "DUPoint.h"
}
using namespace std ;
void OverloadClass::input()
{
char leftParen;
char comma ;
cin >> leftParen >> x_ >> comma;
char rightParen;
cin >> y_ >> rightParen;
}
// Constructor and method implementations
istream& operator>> (istream& in, OverloadClass &p)
{
p.input();
return in;
}
我在 Xcode 中遇到的错误是:
Link ./OverloadDirectory Undefined symbols: "operator>>(std:basic_istream >&, OverloadClass&)" referenced from: _main in overloadtester.o ld: symbol(s) not found collect2: ld returned 1 exit status
目前我无法使用 VS 访问计算机,希望当我这样做时我可以发布在该 IDE 上运行代码时遇到的错误。
根据@Mark 的更多详细信息请求进行了编辑
为响应@sbi 对有关 input() 的更多信息的请求而编辑
最佳答案
错误undefined symbol 是链接器错误。这意味着当您将所有代码链接到单个可执行文件/库时,链接器无法找到函数的定义。主要的两个原因是忘记在库/可执行文件中包含编译对象或定义函数时出错(假设您声明了 void f( int & );
但您实现了 void f( const int & ) {}
).
我不知道你的 IDE(我从来没有真正理解过 Xcode)但是你可以尝试从命令行编译:g++ -o exe input1.cpp input2.cpp input3.cpp ...
关于c++ - Visual Studio 和 Xcode 中的 C++ 运算符重载错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3190700/