首页 > 解决方案 > 如何使用结构体、类型定义和模板?

问题描述

我正在尝试实现以下代码,但由于 ,我不断收到错误typedef,有人可以帮忙吗?

 template<class T>
 struct box{
 T data;
 box *link;
 };
 typedef box* boxPtr;

错误是:

Use of class template 'box' requires template arguments

标签: c++templatestypedef

解决方案


写作

template<class T>
struct box{
    T data;
    box *link;
 
    typedef box<T>* boxPtr; 
};

int main()
{
    box<int>::boxPtr use_of_a_bad_idea;
}

是一种方法,但是将指针类型伪装成对象类型会导致内存泄漏:根据经验不要这样做。是解决这个问题的最好方法。


推荐阅读