什么都一样,同一个类模板,问什么不能调用同一个函数呢?
都是一个类的啊?
#include <iostream>
using namespace std;
template <class T, int n>
class people
{
public:
people();
people(const T & t);
T & operator[](int i);
void show();
private:
T a[n];
};
int main()
{
people<double, 4> one;
people<double, 4>*p=new people<double, 4>[4];
p[3];//为什么这里就不调用operator[]函数呢?
one[3];
return 0;
}
template <class T, int n>
people<T, n>::people()
{
cout<<"不带参数的构造函数\n";
for (int i=0; i<n; i++)
a[i]=(i+1);//给people类的成员赋值
}
template <class T, int n>
people<T, n>::people(const T & t)
{
cout<<"带一个参数的构造函数\n";
for (int i=0; i<n; i++)
a[i]=t;
}
template <class T, int n>
T & people<T, n>::operator[](int i)
{
cout<<"重载operator[]运算符\n";
if (i<0 || i>n)
{
cerr<<"超出限制:第"<<i<<"个元素溢出\n";
exit(EXIT_FAILURE);
}
return a[i];
}
template <class T, int n>
void people<T, n>::show()
{
for (int i=0; i<n; i++)
cout<<"a["<<i<<"]:"<<a[i]<<"\t";
cout<<endl;
}
都是一个类的啊?
#include <iostream>
using namespace std;
template <class T, int n>
class people
{
public:
people();
people(const T & t);
T & operator[](int i);
void show();
private:
T a[n];
};
int main()
{
people<double, 4> one;
people<double, 4>*p=new people<double, 4>[4];
p[3];//为什么这里就不调用operator[]函数呢?
one[3];
return 0;
}
template <class T, int n>
people<T, n>::people()
{
cout<<"不带参数的构造函数\n";
for (int i=0; i<n; i++)
a[i]=(i+1);//给people类的成员赋值
}
template <class T, int n>
people<T, n>::people(const T & t)
{
cout<<"带一个参数的构造函数\n";
for (int i=0; i<n; i++)
a[i]=t;
}
template <class T, int n>
T & people<T, n>::operator[](int i)
{
cout<<"重载operator[]运算符\n";
if (i<0 || i>n)
{
cerr<<"超出限制:第"<<i<<"个元素溢出\n";
exit(EXIT_FAILURE);
}
return a[i];
}
template <class T, int n>
void people<T, n>::show()
{
for (int i=0; i<n; i++)
cout<<"a["<<i<<"]:"<<a[i]<<"\t";
cout<<endl;
}