我正在尝试使用一些功能创建一个自定义命名空间。当我编译我的测试文件时,我收到以下链接器错误:
Undefined first referenced
symbol in file
Direction_ns::operator<<(std::basic_ostream<char, std::char_traits<char> >&, Direction_ns::Direction) /var/tmp//cc3entPx.o
ld: fatal: symbol referencing errors. No output written to a.out
collect2: error: ld returned 1 exit status
这是我的标题:
#ifndef DIRECTION_H
#define DIRECTION_H
#include <iostream>
#include <stdexcept>
#include <string>
namespace Direction_ns{
enum Direction { Up, Down, Left, Right };
extern std::ostream& operator<<(std::ostream&, const Direction);
extern std::istream& operator>>(std::istream&, Direction&);
class bad_direction : public std::runtime_error{
public:
explicit bad_direction(const std::string& what_arg)
: runtime_error(what_arg) {}
};
}
#endif
这是我的来源:
#include <iostream>
#include <string>
#include "Direction.h"
using namespace std;
ostream& Direction_ns::operator<<(ostream& o, const Direction d){
string s;
switch (d){
case 0:
s = "Up";
break;
case 1:
s = "Down";
break;
case 2:
s = "Left";
break;
case 3:
s = "Right";
break;
default:
throw bad_direction("Out of range");
break;
}
o << s;
return o;
}
istream& Direction_ns::operator>>(istream& i, Direction & d){
string str;
if(!(i >> str))
return i;
if(str == "Up")
d = static_cast<Direction>(0);
else if(str == "Down")
d = static_cast<Direction>(1);
else if(str == "Left")
d = static_cast<Direction>(2);
else if(str == "Right")
d = static_cast<Direction>(3);
else
throw bad_direction("Out of range");
return i;
}
这是测试文件:
#include <iostream>
#include "Direction.h"
using namespace std;
using namespace Direction_ns;
int main()
{
for (Direction d = Up; d <= Right; d = static_cast<Direction>(d + 1))
{
cout << d << '\n';
}
return 0;
}