我有一个带有私人朋友操作员<<
它的声明是:
std::ostream& operator<<(std::ostream& out, const Position& position);
在cpp文件中它的定义是:
std::ostream& operator<<(std::ostream& out, const Position& position)
{
out << position.getXPoint() << "," << position.getYPoint();
return out;
}
它正在编译然后链接到使用它的主函数,但是当我使用它时,我得到一个未定义的引用......
但是,当我将定义添加到主 cpp 文件的顶部并删除朋友声明时,它工作正常......
这是我在主要功能中使用它的方式
std::cout << node->getPosition() << std::endl;
不多不少...
这是链接器错误
/home/luke/Desktop/pathfinder/parse_world.cpp:34: 未定义对 `pathfinder::operator<<(std::ostream&, pathfinder::Position const&)' 的引用
这是类标题...
#ifndef PATHFINDER_H
#define PATHFINDER_H
#include <ostream>
#include <istream>
#include <list>
#include <vector>
#include <stdexcept>
#include <cstring>
namespace pathfinder
{
class Node;
typedef unsigned int GCost;
typedef std::vector<std::vector<Node*> > World;
typedef std::vector<Node*> WorldRow;
class Position
{
public:
typedef unsigned int point_type;
private:
point_type* xPoint_;
point_type* yPoint_;
friend std::ostream& operator<<(std::ostream& out, const Position& position);
public:
Position(const point_type& xPoint = 0, const point_type& yPoint = 0);
Position(const Position& position);
Position(Position&& position);
~Position();
Position& operator=(const Position& position);
Position& operator=(Position&& position);
point_type getXPoint() const;
point_type getYPoint() const;
void setXPoint(const point_type& xPoint);
void setYPoint(const point_type& yPoint);
};
class Node
{
private:
bool* isPassable_;
bool* isStartingNode_;
bool* isTargetNode_;
Position* position_;
GCost* additionalGCost_;
Node* parent_;
public:
Node(const bool& isPassable = true, const bool& isStartingNode = false, const bool& isTargetNode = false, const Position& position = Position(0,0), const GCost& additionalGCost = 0, Node* parent = nullptr);
Node(const Node& node);
Node(Node&& node);
~Node();
Node& operator=(const Node& node);
Node& operator=(Node&& node);
bool isPassable() const;
bool isStartingNode() const;
bool isTargetNode() const;
Position getPosition() const;
GCost getAdditionalGCost() const;
Node* getParent() const;
void setAsPassable(const bool& isPassable);
void setAsStartingNode(const bool& isStartingNode);
void setAsTargetNode(const bool& isTargetNode);
void setPosition(const Position& position);
void setAdditionalGCost(const GCost& additionalGCost);
void setParent(Node* parent);
};
class WorldHelper
{
public:
static World fromStream(std::istream& input);
static void syncPositions(World& world);
static void uninitializeWorld(World& world);
static Node* findStartingNode(const World& world);
static Node* findTargetNode(const World& world);
};
class Pathfinder
{
public:
virtual std::list<Node*> operator()(World& world) const = 0;
};
};
#endif //PATHFINDER_H
现在删除朋友声明后,我收到如下错误消息:
无法将 'std::ostream {aka std::basic_ostream}' 左值绑定到 'std::basic_ostream&&'</p>
它与 std::cout 语句发生在同一行...
那么,有什么交易...
提前致谢