2016-11-24 137 views
0

嘿,我创建了一个名为“节点”的抽象类和实现Node类的类NodeBlock。在我的主类,我需要打印的NodeBlock这里面是价值观我的一些主类代码:字符串重载运算符“>>”

//receving the fasteset route using the BFS algorithm. 
std::stack<Node *> fast = bfs.breadthFirstSearch(start, goal); 

/*print the route*/ 
while (!fast.empty()) { 
    cout << fast.top() << endl; 
    fast.pop(); 
} 

节点:

#include <vector> 
#include "Point.h" 
#include <string> 

using namespace std; 

/** 
* An abstract class that represent Node/Vertex of a graph the node 
* has functionality that let use him for calculating route print the 
* value it holds. etc.. 
*/ 
    class Node { 
    protected: 
     vector<Node*> children; 
     bool visited; 
     Node* father; 
     int distance; 

    public: 
     /** 
     * prints the value that the node holds. 
     */ 
     virtual string printValue() const = 0; 

     /** 
     * overloading method. 
     */ 
     virtual string operator<<(const Node *node) const { 
      return printValue(); 
     }; 

    }; 

NodeBlock.h:

#ifndef ADPROG1_1_NODEBLOCK_H 
#define ADPROG1_1_NODEBLOCK_H 

#include "Node.h" 
#include "Point.h" 
#include <string> 


/** 
* 
*/ 
class NodeBlock : public Node { 
private: 
    Point point; 

public:  
    /** 
    * prints the vaule that the node holds. 
    */ 
    ostream printValue() const override ; 
}; 
#endif //ADPROG1_1_NODEBLOCK_H 

NodeBlock.cpp:

#include "NodeBlock.h" 
using namespace std; 



NodeBlock::NodeBlock(Point point) : point(point) {} 

string NodeBlock::printValue() const { 
    return "(" + to_string(point.getX()) + ", " + to_string(point.getY()); 
} 

我删除了这些类的所有不必要的方法。现在我试图超载< <运算符,所以当我从堆栈顶部。()将其分配给“cout”它将打印点的字符串。

,但我的电流输出为: 0x24f70e0 0x24f7130 0x24f7180 0x24f7340 0x24f7500

正如你知道的地址。感谢您的帮助

+1

见本:http://stackoverflow.com/questions/476272/how-to-properly-overload-the-operator-for-an-ostream – qxz

+1

你现在需要一个'friend':) –

+0

'virtual string operator <<(const Node * node)const您正在定义一个运算符,其左侧有一个节点,右侧有一个节点指针,并返回一个字符串。像这样的东西:'节点a;节点b;一个<<&b;'将是该运算符的合法用法,尽管不是非常有用。你可能想要别的东西。 –

回答

1

你要寻找的是一个<<操作是在左侧的ostream和右侧的Node,并评估相同的ostream。因此,应该像这样(的Node类以外)来定义:

std::ostream& operator<<(std::ostream& out, const Node& node) { 
    out << node.printValue(); 
    return out; 
} 

然后,你需要确保你cout荷兰国际集团一Node,而不是一个Node*

cout << *fast.top() << endl; // dereference the pointer 
+0

当我定义自定义类时,你的意思是在课外,但在头部内? – yairabr

+0

该函数必须位于全局范围内,因此您需要在头文件中声明它的签名并将实现放在源文件中。不管什么头文件/源文件,只要它们在合适的时候被包含在内,当然是 – qxz

+0

那么你需要在'Node'的头文件中声明函数。你可以使函数'static'如果你真的想在头文件中,或者只是将它放在任何源文件中。这并不重要;尝试一下,看看你是否得到错误。 – qxz