我有一個模板類matrix
,我嘗試覆蓋對不同矩陣的+
操作。我想覆蓋派生類中的運算符,但有一些錯誤。換句話說,我希望能夠爲matrix
的2個已定義對象僅執行A+B
,而不是執行for
循環。 下面是代碼:C++運算符在派生類中重載
#include<iostream>
using namespace std;
template<class T>
class matrix
{
protected:
T **tab;
int row,col;
public:
matrix(int row,int col)
{
this->row = row;
this->col = col;
tab = new T* [col];
for(int i = 0; i < col; i++)
tab[i] = new T[row];
tab[0][0] = 100;
}
T& operator()(int i,int j)
{
return tab[i][j];
}
T operator()(int i,int j)const
{
return tab[i][j];
}
void operator=(const matrix& that)
{
for(int i = 0; i < col ; i++)
for(int j = 0; j < row ; j++)
tab[i][j] = that.tab[i][j];
}
matrix(const T& tab)
{
row = tab.row;
col = tab.col;
tab = new T* [col];
for(int i = 0; i < col; i++)
tab[i] = new T[row];
}
~matrix()
{
for(int i = 0; i < col; i++)
delete tab[i];
delete tab;
}
};
template<class T>
class Operations: public matrix<T>
{
T& operator+(matrix& tab1,matrix& tab2)
{
int i,j;
ligne = tab.ligne;
col = tab.col;
tab3 = new T* [col];
for(int i = 0; i < col; i++)
tab3[i] = new T[ligne];
for(i = 0; i < col; i++)
for(j = 0; j < ligne; j++)
tab3[i][j] = tab1[i][j]+tab2[i][j];
return tab3;
}
};
int main()
{
matrix<int> tab1(10,10);
matrix<int> tab2(5,5);
cout<<tab1(0,0)<<endl;
tab1(0,0) = 10;
cout<<tab2(0,0)<<endl;
tab2(0,0) = 5;
tab2 = tab1;
tab1(0,0) = 3;
return 0;
}
類matrix
工作正常。這是當我加入了Operations
類,我得到了以下誤差修改:
v2.cpp:65:15: error: declaration of ‘operator+’ as non-function
T& operator+(matrix& tab1,matrix& tab2)
^
v2.cpp:65:13: error: expected ‘;’ at end of member declaration
T& operator+(matrix& tab1,matrix& tab2)
^
v2.cpp:65:21: error: expected ‘)’ before ‘&’ token
T& operator+(matrix& tab1,matrix& tab2)
能否請您給我解釋一下這些錯誤的原因和如何糾正呢? 謝謝
編輯 我想實現+操作作爲matrix
一個成員類的功能,但我得到的錯誤消息:你能告訴我什麼是與方式去錯了我定義operator +?
matrix operator+(const matrix& that)const
{
int i,j;
T** tab3;
tab3 = new T* [col];
for(int i = 0; i < col; i++)
tab3[i] = new T[row];
for(i = 0; i < col; i++)
for(j = 0; j < row; j++)
tab3[i][j] = that.tab[i][j]+tab[i][j];
return tab3;
}
請張貼一個簡單的例子。 – Columbo
這不是運算符重載的工作原理。看到這裏的一些例子:http://en.cppreference。com/w/cpp/language/operators –
爲什麼要讓'Operations'從'matrix'繼承?瘋了吧*! – YSC