通过参考模板和正常函数指针

时间:2015-07-06 05:49:58

标签: c++

这是我的代码:

#include <iostream>


template<typename B>
class test{
    public:
    B* t;

    test(const B& init){
    }   
};



void funct(const int*& test){

}


int main(int argc, char** argv) {

    test<int*> t(new int(2));   // works fine
    funct(new int(2));          //error

    return 0;
}

我试图模仿我的模板类中发生的事情,但不知怎的,我得到了错误。我认为const B& init,其中B int*const int*& init。添加const允许它接受临时&#34;新&#34; s。我做了一个非模板化的函数来测试它,它有这个标题,void funct(const int*& test)。它和上面一样,但是怎么会不会new int(2)

1 个答案:

答案 0 :(得分:4)

<script> .......... .......... frameDoc.body.innerHTML='<div><br><ul>'; for( l = 0; l < k; l++ ) { var tmp1=searched_headings_filename[l]; var tmp2=searched_headings[l]; frameDoc.body.innerHTML+='<div style="margin-left:10;"><li class="highlight"><a href="'+tmp1+'" onclick="highlightSearch();">'+searched_headings[l]+'</a></li></div>'; } frameDoc.body.innerHTML+='</ul></div>'; .......... .......... </script> <script> function highlightSearch() { alert('Successfully highlighted'); } </script> 表示“引用指向const int*&的指针。您需要const int应用于指针,而不是const

int

这是模板版本的功能。 void funct(int* const& test){} 是指向T的指针,因此int实际上是指向T&的指针。该模板不会为int执行T的文本替换。它替换类型。如果您使用int*typedef int* X,则会得到相同的结果。