Des*_*tor 1 c++ arrays templates compiler-errors
我知道数组索引在C&C++中是可交换的,因此a [i]与i [a]相同,它与i [a]具有相同的效果,并且两者都是有效的.但是最近我写了一个下面的程序,当我使用i [intob]而不是intob [i]时无法编译.
#include <iostream>
#include <cstdlib>
using std::cout;
template<class T>class atype
{
T* a;
int size;
public:
atype(int n)
{
size=n;
a=new T[size];
for(auto i=0;i<size;i++)
a[i]=i;
}
~atype()
{
delete[] a;
}
T& operator[](int i);
};
template<class T> T& atype<T>::operator[](int i)
{
if(i<0 || i>size)
{
cout<<"\nIndex value of ";
cout<<i<<" is out of bounds.\n";
exit(1);
}
return a[i]; // i[a] also works fine here.
}
int main()
{
int i,n;
cout<<"Enter value of n: ";
std::cin>>n;
atype<int> intob{n};
atype<long int> longintob{n};
cout<<"Integer array: ";
for(i=0;i<n;i++)
intob[i]=i;
for(i=0;i<n;i++)
cout<<i[intob]<<' '; // oops compiler error why???
cout<<'\n';
cout<<"long integer array: ";
for(i=0;i<n;i++)
longintob[i]=i;
for(i=0;i<n;i++)
cout<<longintob[i]<<' ';
longintob[15]=123;
}
Run Code Online (Sandbox Code Playgroud)
我得到以下编译器错误.
[错误]'运算符[]'不匹配(操作数类型为'int'和'atype')
但是,如果我在重载[]运算符函数中编写i [a],那么它可以正常工作.为什么?
是否存在使用i [intob]访问数组元素的解决方案?
告诉我如果我在某个地方错了并且错误地理解了某些东西.
索引操作符本身不可交换.
如果您理解对于数组(或指针)a
和索引等于,i
则会a[i]
有所帮助*(a + i)
.可交换位来自该添加,因为*(a + i)
它等于*(i + a)
导致i[a]
有效.
归档时间: |
|
查看次数: |
65 次 |
最近记录: |