簡體   English   中英

通過引用傳遞模板函數C ++

[英]Pass by reference with template functions C++

我正在嘗試制作一個模板函數,並通過引用將兩個變量傳遞給它,每件事聽起來都不錯,但從未編譯過,錯誤消息是:-

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 */ 
}

您需要在函數Read_Data的聲明中指定返回值類型。

一些例子:

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

如果您不打算在該函數中返回任何內容,則第一個示例可能是您需要的...

順便說一句,您還需要:

  • 在函數main ,將int arr更改為int* arr
  • main函數中,將Read_Data更改為Read_Data<int>
  • main函數中,使用完后調用delete[] arr
  • 在函數Read_Data ,將type &arr更改為type* &arr

您只是缺少一些東西來進行代碼編譯(解決了您看到的錯誤)。

基本上,在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 
     */ 
}   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM