1

我有这个运营​​商

Mtx Mtx::operator*(const Vtr &rhs) const
{
Mtx Q(nrows, ncols, 0);

for (int i = 0; i < nrows; ++i) {
    for (int j = 0; j < ncols; ++j) {
        Q.ets[i][j] = 0.0;

        for (int k = 0; k < rhs.length; ++k) {
            Q.ets[i][j] += ets[i][k] * rhs.ets[k];
        }
    }
  }
return Q;
}

我调用这个运算符M3 = M1 * V1,我收到编译器错误,因为lengthets[k]第三个循环中是类的私有成员Vtr。我怎样才能访问它们?

4

3 回答 3

4

Let Mtx be a friend of Vtr.

 class Vtr {
     friend class Mtx;
     //...
 };

Or let the Mtx::operator* method be a friend.

 class Vtr {
     friend Mtx Mtx::operator*(const Vtr &) const;
     //...
 };

Either of these changes will let your current implementation work without any further changes.

于 2012-07-27T05:17:52.027 回答
4

例如,成为数据Mtx的朋友Vtr或提供对数据的公开评估

class Vtx {
 public:
  const SomeType& operator[](unsigned int i) const { return ets[i]; }

};

这实际上将数据访问与底层实现分离,因为操作符可以以不同的方式实现。

另一方面,它提供了对底层表示的直接访问,因此它添加了一个约束,即您不能以更改给定索引和给定元素之间的映射的方式更改实现。

于 2012-07-27T05:22:17.873 回答
2

Friend is your answer!!

Either you can make the class a friend or the function.

But I'm not sure if that is the correct logic for you case.

Mostly if you cant access a variable that means you shouldn't access it.

Check if you are doing correctly with access specifiers. And the only way to go about is friend then use 'friend' function or class.

于 2012-07-27T05:18:57.820 回答