C ++使用它来使用访问器

问题描述 投票:-1回答:2

我在类SparseMatrix中构建了一个访问器。我正在尝试编写成员函数symmetric,我想使用我的访问器访问对称函数中的类私有数据。

我有一个转置成员函数,this->transpose()按照我的想法工作。因此,我尝试了this->[],但它当然不起作用。可能是因为运算符重载。

bool SparseMatrix::symmetric() const
{
  SparseMatrix A_T(m_m,m_n);
  A_T = this->transpose();
  bool is_symmetric;
  for (int row=0; row<m_m; ++row)
    {
      int cols = A_T.m_colIndex[row].size();
      for (int col=0; col<cols; ++col)
        {
          array<int, 2> A_tuple  = {row,m_colIndex[row][col]};
          array<int, 2> A_T_tuple  = {row,A_T.m_colIndex[row][col]};
          if (A_T[A_T_tuple] == this->operator[](A_tuple))
            {
              is_symmetric = true;
            }
...

为了清楚起见添加了更多代码。

这里是错误消息。

Undefined symbols for architecture x86_64:
  "SparseMatrix::operator[](std::__1::array<int, 2ul>&) const", referenced from:
      SparseMatrix::symmetric() const in SparseMatrix.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
c++ this
2个回答
0
投票

我是否正确,this实现了operator[]?如果是这样,请使用this->operator[](/*arguments*/)代替this->[]


0
投票

只需将星号放在大括号内:

(*this)[some_index];

这是必需的,因为取消引用运算符*的优先级低于下标运算符。


对于更新的问题:

您似乎已声明但尚未定义constoperator[]版本,因为您得到的是链接错误而不是编译错误。您需要为此operator[]() const提供一个正文,以便可以从symmetric方法中使用它。您不能通过const方法使用非const运算符。

© www.soinside.com 2019 - 2024. All rights reserved.