1

我正在尝试使用一些功能创建一个自定义命名空间。当我编译我的测试文件时,我收到以下链接器错误:

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;
}
4

2 回答 2

0

您可能忘记同时构建Direction.cpptest.cpp

g++ test.cpp Direction.cpp在我的环境中运行良好(gcc 版本 4.7.2 (Debian 4.7.2-5))。

但是,尝试仅构建 test.cpp 会导致以下错误:

test.cpp:(.text+0x1c): undefined reference to `Direction_ns::operator<<(std::ostream&, Direction_ns::Direction)'`
于 2013-06-03T16:29:50.530 回答
0

标题说这operator<<(std::stream&, const Direction)是在命名空间中定义的Direction_ns。第一个源文件operator<<(std::stream&, const Direction)在全局命名空间中有一个定义。命名空间中没有定义Direction_ns

于 2013-06-03T17:19:32.723 回答