我已经为链表中的节点制作了一个模板类,并尝试通过重载<<将其内容输出到输出流中。然而,我的当前代码:
#include <iostream>
using namespace std;
template<class NType> class Node;
template<class NType>
class Node {
private:
void deletePointer(NType* p);
public:
NType data;
Node *prev, *next;
template<typename T>
struct is_pointer { static const bool value = false; };
template<typename T>
struct is_pointer<T*> { static const bool value = true; };
Node();
Node(NType data);
~Node();
};
int main() {
Node<int> *n1 = new Node<int>();
Node<int> *n2 = new Node<int>(10);
std::cout << "Node 1: " << n1 << std::endl;
std::cout << "Node 2: " << n2 << std::endl;
}
template<class NType> inline std::ostream & operator << (std::ostream& out, const Node<NType> &node){
out << node.data;
return out;
}
template<class NType> inline Node<NType>::Node()
:data(NULL), prev(NULL), next(NULL)
{
}
template<class NType> inline Node<NType>::Node(NType data)
:data(data), prev(NULL), next(NULL)
{
}
template<class NType> inline Node<NType>::~Node(){
if(is_pointer<NType>::value){
deletePointer(&data);
} else {
return;
}
}
template<class NType> inline void Node<NType>::deletePointer(NType* p){
delete p;
}
输出节点中的内存位置,而不是数据。这种情况发生在原始类型,如int
等,就好像它不知道NType
容器中有什么样的数据。
Node 1: 0x741010
Node 2: 0x741030
Node 3: 0x741070
Node 4: 0x741090
我尝试使用
typename
而不是 class
,但仍然无法成功...是否有办法在插入之前动态查找模板正在使用的类型并进行转换或其他操作?我知道我可以为所有基本类型编写大量冗余代码,但这似乎是浪费和不必要的。如果有帮助的话,我正在 Arch Linux x64 上使用 GCC v4.6.2 20111223 进行编译。
编辑:由于很多人都提到了它。我还尝试将类放在外部作为友元和独立函数,但无论我把它放在哪里,流输出的都是地址而不是数据本身。没有私有数据值需要访问,因此不需要成为友元。
编辑: 测试用例:http://ideone.com/a99u5 同时更新了上面的源代码。
编辑: 添加了我的代码剩余部分,以帮助 Aaron 理解代码。
SomeNode << cout
,这显然不是你想要的。ostream& operator<<
应该通常作为一个自由函数,因为你希望ostream
在左侧。修复这个问题不一定能解决你的问题,但是... - Lightness Races in Orbit