当将数组对象作为实参传入函数的时候,数组对象会“退化”为指针,而sizeof(指针)得到的只是指针的大小,所以我们在这里使用传引用传参。
#include<iostream>
using namespace std;
//模板函数,计算数组的大小,通过传引用传参,可以保证sizeof 得到的为数组的实际空间大小
template<typename T>
int count_arr(T & a)
{
return sizeof(a)/sizeof(a[0]);
}
class Student
{
int data;
char *name;
};
//template<typename T>
//int count_arr_ptr(T
int main()
{
int test[100];
cout<<count_arr(test)<<endl;
Student *stu=new Student[20];
cout<<count_arr(stu)<<endl;
cout<<"sizeof Student:"<<sizeof(Student)<<endl;
cout<<"sizeof stu:"<<sizeof(stu)<<endl;
Student stud[55];
cout<<"sizeof Stud:"<<count_arr(stud)<<endl;
return 0;
}
结果如下: