在我的类的公共(public)方法中访问溢出的方括号时遇到问题。这是代码:
#include <iostream>
#include <cassert>
#include <cmath>
using namespace std;
template<unsigned int DIM> class Vector
{
private:
double mData[DIM];
public:
Vector(double tableau[DIM])
{
for(int i=0; i<DIM; i++)
{
mData[i] = tableau[i];
}
}
double operator[](int index)
{
assert(index < DIM);
assert(index > -1);
assert(-pow(10,-6)<=mData[index]<=1+pow(10,-6));
if(mData[index]>=0 && mData[index]<=1)
{
return mData[index];
}
else if(mData[index]<0 && mData[index]>=pow(10,-6))
{
return 0.0;
}
else if(mData[index]>1 && mData[index]<= 1+ pow(10,-6))
{
return 1.0;
}
}
double getDim() const
{
return DIM;
}
void print() const
{
for(int i=0;i<getDim();i++)
{
cout << this[i] << " "; //PROBLEM!!
}
}
};
int main()
{
double err=pow(10,-6);
double tableau[5];
tableau[0] = 0.5;
tableau[1] = 0.79;
tableau[2] = err;
tableau[3] = 1+err;
tableau[4] = 0;
Vector<5> proba(tableau);
proba.print();
}
我已经尝试过 *this、this->,但似乎任何东西都有效。 我希望你能帮助我。 佛罗伦萨
最佳答案
成员运算符重载需要类类型的值或引用,this
是一个指针。因此,您要么需要在使用运算符之前取消引用 this
指针,如下所示:
(*this)[i]
或者您可以直接调用操作符,其优点是其意图完全明确,但缺点是有点冗长和晦涩(因此更有可能使阅读它的人绊倒) :
this->operator[](i)
如果您已经尝试过 *this[i]
并发现它没有解决问题,那是因为它实际上意味着 *(this[i])
!
关于c++ - 这个指针和方括号重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26892514/