c++ - 通过模板函数 C++ 的引用传递

标签 c++ templates pass-by-reference

我正在尝试制作一个模板函数并通过引用将两个变量传递给它,一切听起来都不错,但它从未编译过,错误消息是:-

error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

我试了一小部分代码,它给了我同样的错误,请帮忙吗??

这部分代码,所有其他代码都是这样的:

int size , found = -1 ; 

template<class type> Read_Data( type &key , type &arr)
{ 
    cout << " please enter the size of your set \n " ; 
    cin >> size ;
    arr = new type[size]; 

    cout << " please enter the elements of your set : \n " ;
    for (int i = 0 ; i <size ; i ++ )
    {
        cout << " enter element number " << i << ": "  ;  
        cin >> arr[i] ;
    }
    cout << " please enter the key elemente you want to search for : \n " ;
    cin >> key ; 
}

void main(void)
{ 
    int key , arr ; 
    Read_Data (key, arr);

    /*after these function there is two other functions one to search for key 
    in array "arr" and other to print the key on the screen */ 
}

最佳答案

您只是缺少一些东西来编译代码(解决您看到的错误)。

基本上,在int main()中,需要在实例化模板时指定类型,如:

Read_Data <int> (key, value); 

这样编译器就知道你真正想用什么类型来实例化它。

另请注意,数组的类型应为 int *。所以在模板函数中,签名必须更改为:

template<class type> Read_Data( type &key , type* &arr)

这是更正后的代码,不会显示您之前看到的错误:

#include<iostream>  

using namespace std;

int size , found = -1 ; 

template<class type> void Read_Data( type &key , type* &arr)
{ 
    cout << " please enter the size of your set \n " ; 
    cin >> size ;
    arr = new type[size]; 
    cout << " please enter the elements of your set : \n " ;

    for (int i = 0 ; i <size ; i ++ )
    {   
        cout << " enter element number " << i << ": "  ;   
        cin >> arr[i] ;
    }   

    cout << " please enter the key elemente you want to search for : \n " ;
    cin >> key;                                                                                                                                         
}

int main()
{   
    int key;
    int * arr;
    Read_Data<int> (key, arr);

    /* after these function there is two other functions one to search for key 
     * in array "arr" and other to print the key on the screen 
     */ 
}   

关于c++ - 通过模板函数 C++ 的引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22434783/

相关文章:

c++ - 在opencv中从Mat图像创建多个子图像?尝试为每个连接的组件创建子图像

c# - 为什么我返回的对象与我收到的对象不匹配?

c - 通过引用传递流

javascript - Angular 中的路由

javascript - 传递给函数的数组不会发生变化?

c++ - 在 C++ 中按值迭代?

c++ - 我可以在 C++ 中返回选定的引用吗?

c++ - 通过 Alpha 混合的 OpenGL 掩蔽

templates - GitHub:Template 和 Fork 概念之间有什么区别以及何时使用?

c++ - 是否会为非类型模板参数的不同值实例化新类