【发布时间】:2021-09-21 13:31:34
【问题描述】:
我的终端消息
zo@laptop:~/Desktop$ g++ stack.cpp
stack.cpp: In function ‘int main(int, char**)’:
stack.cpp:50:19: error: no matching function for call to ‘boyInitial(Boy [boyNumber])’
boyInitial(boy);
^
stack.cpp:17:6: note: candidate: template<class T, int N> void boyInitial(T (&)[N])
void boyInitial(T (&boy)[N]){
^~~~~~~~~~
stack.cpp:17:6: note: template argument deduction/substitution failed:
stack.cpp:50:19: note: variable-sized array type ‘long int’ is not a valid template argument
boyInitial(boy);
^
stack.cpp:51:19: error: no matching function for call to ‘getBoyAges(Boy [boyNumber])’
getBoyAges(boy);
^
stack.cpp:34:6: note: candidate: template<class T, int N> void getBoyAges(T (&)[N])
void getBoyAges(T (&boy)[N]){
^~~~~~~~~~
stack.cpp:34:6: note: template argument deduction/substitution failed:
stack.cpp:51:19: note: variable-sized array type ‘long int’ is not a valid template argument
getBoyAges(boy);
我的程序
#include <iostream>
class People{
public:
char *name;
int age;
};
class Boy : public People{
public:
void say(void){
std::cout << "i`m the most handsome!" << std::endl;
}
};
template<class T, int N>
void boyInitial(T (&boy)[N]){
int i;
for(i=0;i<N;i++){
std::cout << "please input boy No." << i+1 << "`s age" << std::endl;
std::cin >> boy[i].age;
}
}
template<class T, int N>
void getBoyAges(T (&boy)[N]){
int i;
for(i=0;i<N;i++){
std::cout << boy.age << std::endl;
}
}
int main(int argc, char **argv){
using namespace std;
int boyNumber = 0;
cout << "how many boys do you want?" << endl;
cin >> boyNumber;
Boy boy[boyNumber];
boyInitial(boy);
getBoyAges(boy);
return 0;
}
说明
我试图通过引用将男孩类型的数据男孩传递给函数 boyInitial() 和 getBoyAges(),然后我得到这样的错误。
感谢您的帮助!
【问题讨论】:
-
variable-sized array type ‘long int’ is not a valid template argument说明一切。 -
这不是 C++ 模板的明智用例
-
请勿发布代码图片。
-
这是我第一次在这个网站上问,我会记住不要在图片中发布代码。感谢大家的快速响应,这出乎我的意料!
-
当我将图像更改为代码文本时。它说“请添加更多细节,你的代码太多了”,所以也许我会把图片留在这里。无论如何,谢谢!
标签: c++ templates function-declaration variable-length-array