簡體   English   中英

從另一個成員函數的實現中調用成員函數

[英]Calling member function from another member function's implementation

因此,我為娛樂和學習定義了平方矩陣的類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 intvectorvector 但是,這沒有編譯,所以我去尋找成員函數指針並寫道:

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< std::vector<long long int> >不兼容

我怎么了?

我想你想要的是:

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

不知道什么樣的矩陣運算的你實際上是試圖做的,但如果你想采取的子矩陣this ,然后通過一個常數乘以42,那么你只需要調用submat(srow, scol)

按照編寫方式,您正在嘗試調用向量的成員函數,而不是包含向量的類的成員函數。

C ++還允許您調用this->submat(srow, scol) ,這可以使您更清楚地了解自己的實際工作,但大多數情況下,您會看到人們在不引用this調用成員函數,因為其完全有效而且更短。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM