我今天开始用C++学习模板,我试着写了一个简单的代码。然后我想使用模板参数(a)在原始函数(function)中编写另一个函数(display),但我找不到正确定义“display”函数的方法。有什么办法可以通过编译吗?还是应该使用class template(这个我还没有研究过,如果需要的话,我会马上看相关资料)?顺便说一句,我的母语不是英语,所以我用了一个小翻译器。我的某些描述可能看起来很奇怪,对此我深表歉意。
我了解到模板有其可变范围,所以我尝试添加{},但它不起作用。更重要的是,我不想将代码复制到“函数”中,所以我不知道该怎么做。
template <typename T>
void function(T a[],int n)
{
cout<< "now you are in function." <<endl;
for(int i = 0; i < n; i++)
{
display(a,i);//Here I have to use "a"
cout << a[i] << " ";
}
cout << endl;
}
void display(T a[],int n)
{
cout << "now you are in display." << endl;
for(int i = 0; i < n; i++)
{
cout << a[n-i] << " ";
}
cout << endl;
}
这是编译器说的: 错误:变量或字段“显示”声明无效 void display(T a[],int n) 错误:“T”未在此范围内声明 但是我不能在“显示”功能之前使用其他类型名称。
最佳答案
您的代码有两个问题:
-
display
在function
之后定义, 因此不能在function
内使用;和 -
display
应该是一个模板函数,以便使用类型名称T
.
自 display
在 function
之后定义,编译器将无法找到 display
当您尝试在 function
内调用它时.您可以声明 display
在定义 function
之前,这基本上告诉编译器该函数在其他地方定义,或者您可以移动 display
的定义在`函数之上。
另外,你需要制作display
还有一个模板,以便它可以使用类型 T
.
您可以通过执行以下操作以最简单的方式解决这两个问题:
template <typename T>
void display(T a[],int n)
{
// your code here
}
template<typename T>
void function(T a[],int n)
{
// your code here
}
如果您真的想要 display
的定义在function
之后, 你可以声明 display
之前function
定义:
template<typename T>
void display(T a[], int n);
template<typename T>
void function(T a[], int n)
{
// your code here
}
template<typename T>
void display(T a[], int n)
{
// your code here
}
编辑:更新后display
要成为模板,您需要更新代码以相应地调用它:
template<typename T>
void function(T a[], int n)
{
// ... beginning of the function ...
for (int i = 0; i < n; i++)
{
display<T>(a, i); // Note the addition of the template parameter
cout << a[i] << " ";
}
// ... rest of the function ...
}
关于c++ - 如何定义函数模板中使用的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57875004/