c++ - 这个指针和方括号重载

标签 c++ operator-overloading this

在我的类的公共(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/

相关文章:

c++ - 编译器在数组到指针衰减存储中生成的指针存储在哪里?

c++ - 参数有几行的宏​​函数?

c++ - 将矩阵 `(*sp)[i]` 的行 `shared_ptr<vector<vector<T>> sp` 传递给接受 `shared_ptr<vector<T>>` 的函数

c# - 需要重载 operator< 和 null 检查

javascript - jQuery 选择器上下文 : this or $(this)

c++ - 每个 c++ 成员函数是否都隐含地将 `this` 作为输入?

c++ - 指向共享对象的指针数组

c++ - Operator [] 作为非静态函数

c++ - 如何重载数组索引运算符的多个下标?

javascript - 为什么我们在 Angular 上将 Controller 变量设置为 "this"?