【发布时间】:2012-02-07 11:01:12
【问题描述】:
我为链表中的节点创建了一个模板类,我试图通过重载
#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<<通常应该始终是免费功能,因为您需要 LHS 上的ostream。解决这个问题不一定能解决您的问题,但是... -
请制作一个测试用例。 ideone.com
标签: c++ templates operator-overloading