【问题标题】:Calling member function from another member function's implementation从另一个成员函数的实现中调用成员函数
【发布时间】:2017-09-01 22:56:39
【问题描述】:

所以我定义了一个方阵类sqmatrix 用于娱乐和学习,并且我已经成功定义了一个函数submat,它输出以某种方式构造的对象的子矩阵:

sqmatrix sqmatrix::submat (unsigned int row, unsigned int col)
{ /* code */   return smat;    }

现在我想定义另一个函数,它接受由submat 构造的子矩阵并输出,比如说,所有元素都乘以42 的矩阵。为此,我写了

sqmatrix sqmatrix::cofact (unsigned int srow, unsigned int scol)
{
   sqmatrix cfac = 42 * m_mat.submat(srow, scol);
   return cfac;
}

我之前重载了* 以使用我的对象,并且m_mat 已在类的标题中声明为包含long long ints 的vectors 的vector。但是,这并没有编译,所以我去找成员函数指针并写道:

sqmatrix sqmatrix::cofact (unsigned int srow, unsigned int scol)
{
   sqmatrix (sqmatrix::*point)(unsigned int, unsigned int);
   point = &sqmatrix::submat;
   sqmatrix cfac = 42 * (m_mat.*point)(srow, scol);
   return cfac;
}

但是,这也不能编译。以下是头文件中的相关行:

private:
 // ...
 std::vector< std::vector<long long int> > m_mat;
public:
 // ...
 sqmatrix submat(unsigned int row, unsigned int col);
 sqmatrix cofact(unsigned int srow, unsigned int scol);

编译器说:

错误:指向成员类型sqmatrix (sqmatrix::)(unsigned int,unsigned int)的指针与对象类型std::vector&lt; std::vector&lt;long long int&gt; &gt;不兼容

我做错了什么?

【问题讨论】:

  • 我认为您的问题是您试图在 std::vector (m_mat) 的实例上调用 submat() .. submat() 是 sqmatrix 的成员函数
  • m_matvectorvectors。 vectors 没有 submat 方法并且不能调用 sqmatrix 方法指针..
  • 你想做什么?你的指针成员 voodoo 似乎等同于m_mat.submat(srow, scol),这显然是行不通的,因为m_mat 没有这个方法,它不是sqmatrix。指向成员的指针不会神奇地让您从一种类型调用另一种类型的方法,它甚至可能意味着什么?
  • 那么如何在我应用cofact 的对象上调用submat?要构造cofact 的输出,我需要先将对象发送到submat,然后对生成的矩阵做一些事情...
  • 您应用cofact 的对象是*this,而不是m_mat。也许你应该在this 上致电submat。我不确定,你的设计很奇怪。很难读懂意图。

标签: c++ class vector member-functions


【解决方案1】:

嗯。我想你想要:

sqmatrix sqmatrix::cofact (unsigned int srow, unsigned int scol)
{
   sqmatrix cfac = 42 * submat(srow, scol);
   return cfac;
}

不知道您实际尝试执行哪种矩阵运算,但如果您尝试获取 this 的子矩阵,然后将其乘以常数 42,那么您只需要调用 submat(srow, scol) .

按照您编写的方式,您尝试调用向量的成员函数,而不是包含向量的类的成员函数。

C++ 还允许您调用 this-&gt;submat(srow, scol),这可能会让您更清楚您实际在做什么,但大多数时候您会看到人们调用成员函数而不引用 this,因为它完全有效的 C++ 和也更短。

【讨论】:

  • 谢谢。正如我所说,当我发布时我不知道this。您的解决方案帮助了我
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 2011-06-23
  • 2016-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多