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;
}
I'm trying to deliver Boy-type data boy, to the functions boyInitial() and getBoyAges(), by means of references, and then I get such errors.
I am trying to imitate the code here, and then get the errors.
I`d appreciate your help!
The key error message is the following
note: variable-sized array type ‘long int’ is not a valid template argument
You declared a variable length array (the size of the array is not a constant expression)
int boyNumber = 0;
cout << "how many boys do you want?" << endl;
cin >> boyNumber;
Boy boy[boyNumber];
that is not a standard C++ feature.
Instead of variable length arrays use the standard container std::vector
.
The presented last program works because there is no variable length array. The size of the array is known at the compile time.
At least you could declare the functions like for example
template<class T>
void boyInitial(T *boy, size_t n ){
for( size_t i=0; i < n; i++){
std::cout << "please input boy No." << i+1 << "`s age" << std::endl;
std::cin >> boy[i].age;
}
}
The function can be called like
boyInitial( boy, boyNumber );