[英]c++ matrix class: overloading assignment operator
我在為矩陣類實現賦值運算符時遇到了一些麻煩。 似乎編譯器不想識別我的重載賦值運算符(我認為嗎?),我不確定為什么。 我知道有一些有關在c ++中實現矩陣類的各種問題的互聯網文章(這已經幫助了我),但是這次我似乎無法將當前的困境與已經存在的任何其他幫助並列。 無論如何,如果有人可以幫助解釋我在做什么錯,我將不勝感激。 謝謝!
這是我的錯誤消息:
In file included from Matrix.cpp:10:
./Matrix.h:20:25: error: no function named 'operator=' with type 'Matrix &(const Matrix &)'
was found in the specified scope
friend Matrix& Matrix::operator=(const Matrix& m);
^
Matrix.cpp:79:17: error: definition of implicitly declared copy assignment operator
Matrix& Matrix::operator=(const Matrix& m){ //m1 = m2
^
Matrix.cpp:89:13: error: expression is not assignable
&p[x][y] = m.Element(x,y);
~~~~~~~~ ^
3 errors generated.
這是我的.cpp文件中的賦值運算符代碼:
Matrix& Matrix::operator=(const Matrix& m){ //m1 = m2
if (&m == this){
return *this;
}
else if((Matrix::GetSizeX() != m.GetSizeX()) || (Matrix::GetSizeY()) != m.GetSizeY()){
throw "Assignment Error: Matrices must have the same dimensions.";
}
for (int x = 0; x < m.GetSizeX(); x++)
{
for (int y = 0; y < m.GetSizeY(); y++){
&p[x][y] = m.Element(x,y);
}
}
return *this;
這是我的矩陣頭文件:
class Matrix
{
public:
Matrix(int sizeX, int sizeY);
Matrix(const Matrix &m);
~Matrix();
int GetSizeX() const { return dx; }
int GetSizeY() const { return dy; }
long &Element(int x, int y) const ; // return reference to an element
void Print() const;
friend std::ostream &operator<<(std::ostream &out, Matrix m);
friend Matrix& Matrix::operator=(const Matrix& m);
long operator()(int i, int j);
friend Matrix operator*(const int factor, Matrix m); //factor*matrix
friend Matrix operator*(Matrix m, const int factor); //matrix*factor
friend Matrix operator*(Matrix m1, Matrix m2); //matrix*matrix
friend Matrix operator+(Matrix m1, Matrix m2);
您的賦值運算符應該是成員函數,而不是friend
。 您的其他運算符應將參數設為const Matrix &
,否則,將復制該運算符使用的Matrix對象。
您正在獲取元素的地址:
&p[x][y] = m.Element(x,y);
當您想分配給它時,如下所示:
p[x][y] = m.Element(x,y);
friend Matrix& Matrix::operator=(const Matrix& m);
由於必須將operator=
定義為類中的成員函數,因此上述部分沒有什么意義。
實際上,我認為如果您避免了這里(或至少很多朋友)對朋友的需求,您的生活會輕松很多。 矩陣的自足公共接口應該允許您實現所有所需的運算符,無論它們是否是類的成員。
也許您應該尋求的第一件事就是自給自足的公共接口,這樣您實際上就不需要像矩陣乘法運算符這樣的朋友了,因為否則,很可能的誘惑就是使每個涉及矩陣的運算都需要訪問矩陣內部。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.