【问题标题】:Operator() as a subscript for a Matrix classOperator() 作为 Matrix 类的下标
【发布时间】:2012-12-02 11:03:31
【问题描述】:

通过关注此站点C++ FAQ,我为我的 Matrix 类重载了一个 operator()。这是我的课:

class Matrix
{
    public:
    inline float& operator() (unsigned row, unsigned col)
    {
        return m[row][col];
    }

    private:
    float m[4][4];
};

现在我可以像这样在主函数中使用它:

int main()
{
    Matrix matrix;
    std::cout << matrix(2,2);
}

但现在我想用这样的指针来使用它:

int main()
{
    Matrix matrix;
    Matrix* pointer = &matrix;
    std::cout << pointer(2,2);
}

并且编译器告诉指针不能用作函数。有什么解决办法吗?

【问题讨论】:

  • 还提供 'inline const float & operator()' 以便能够从 const 矩阵对象调用。

标签: c++ matrix operator-overloading


【解决方案1】:

您要么需要取消引用它:

(*pointer)(2,2)

或者你需要用它的全名打电话给接线员:

pointer->operator()(2,2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 2023-02-23
    相关资源
    最近更新 更多