[英]Assignment operator of template class c++
永遠不會調用賦值運算符重載。
在1.的主文件中,調用復制構造函數;在2.的主文件中,首先被調用的是operator +,然后是operator *,然后是默認的賦值運算符。
有什么原因嗎?
template<int r, int c, class F = int>
class Matrix {
public:
Matrix(){
int i, j;
data = new F[(r*c)];
for (i = 0; i < c; i++){
for (j = 0; j < r; j++){
data[j + (i*c)] = 0;
}
}
}
...
Matrix(const Matrix& a){
int i=r, j=c;
data = new F[(r*c)];
for(i = 0; i < r; i++){
for(j = 0; j < c; j++){
data[j+(i*c)] = a.data[j+(i*c)];
}
}
}
**Matrix operator=(const Matrix a){
int i, j;
if (data != NULL){
delete data;
data = NULL;
}
data = new F[(r*c)];
for(i = 0; i < r; i++){
for(j = 0; j < c; j++){
data[j+(i*c)] = a.data[j+(i*c)];
}
}
return *this;
}**
friend Matrix operator+( Matrix<r, c, F>& a, int b){
Matrix<r, c, F> temp;
int i, j;
for(i = 0; i < r; i++){
for(j = 0; j < c; j++){
temp.data[j+(i*c)] = a.data[j+(i*c)] + b;
}
}
return temp;
}
Matrix operator*(const int a){
Matrix <r, c, F> temp(*this);
int i, j;
for(i = 0; i < r; i++){
for(j = 0; j < c; j++){
temp.data[j+(i*c)] *= a;
}
}
return temp;
}
...
~Matrix(){
delete[] data;
data = NULL;
}
private:
F *data;
};
int main( ) {
...
Matrix<4, 4> identity(1);
std::cout << identity << std::endl;
1.**Matrix<4, 4> res = identity;**
Matrix<4, 4> identity_2(1);
std::cout << identity _2<< std::endl;
2.**Matrix<4, 4> res_2 = (identity_2 + 2) * 3;**
...
friend Matrix operator+( Matrix<r, c, F>& a, int b){
Matrix<r, c, F> temp;
int i, j;
for(i = 0; i < r; i++){
for(j = 0; j < c; j++){
temp.data[j+(i*c)] = a.data[j+(i*c)] + b;
}
}
return temp;
}
此代碼使運算符的非成員和成員語法混亂。
friend Matrix operator+( Matrix<r, c, F>& a, int b);
表示“有一個非成員函數可以訪問我的內部”。 但是您定義的定義了一個成員函數,該成員函數應具有語法
Matrix operator+(int b) {
由於this
是成員函數,因此被暗示。 有關討論細微差別的示例, 請參見此答案 。
同樣,您的賦值運算符不正確。
Matrix& operator=(const Matrix& a) {
是最常見的形式,盡管參數的格式可以更改,但您需要返回一個返回值的引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.