gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:38:02 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com