我在C++中重載運算符+ =和+時出現問題。我有以下幾點,我不知道爲什麼..「無效的操作數到二進制表達式(Matrice *和Matrice *)你有什麼想法爲什麼?謝謝。重載操作符+ =和+矩陣C++
NB:operator = does work。
的main.cpp
#include <iostream>
#include <cmath>
using namespace std ;
#include "Matrice.hpp"
int main() {
double *tableau = new double[2*2]{1,4,3,2} ;
double *tableau1 = new double[2*2]{1,6,4,-2} ;
Matrice * A = new Matrice(2, tableau) ;
Matrice * B = new Matrice(2, tableau1) ;
Matrice * C = new Matrice() ;
C = A+B ;} // error appears here
Matrice.cpp
#include "Matrice.hpp"
Matrice::Matrice(const Matrice& m) : dim(m.dim), coeffs(new double[m.dim*m.dim]){
for(int i=0; i<dim*dim; i++) {
coeffs[i] = m.coeffs[i] ;
}
}
Matrice::~Matrice() {
delete [] coeffs ;
}
Matrice.hpp
#ifndef Matrice_hpp
#define Matrice_hpp
#include <iostream>
using namespace std ;
class Matrice {
private :
unsigned int dim;
double * coeffs ;
public :
Matrice() {
dim = 2 ;
coeffs = new double[dim*dim] ;
for(int i=0; i<dim*dim; i++) {
coeffs[i] = 0 ;
}
}
Matrice(unsigned int n, double* v) : dim(n), coeffs(new double[dim*dim]) {
if(v) { for(int i=0; i<dim*dim; i++) { coeffs[i] = v[i] ;}
}
else { for(int i=0; i<dim*dim; i++) coeffs[i] = 0 ; }
}
Matrice(const Matrice&) ;
~Matrice() ;
int dimension() const {return dim;}
void modifier(int position, int valeur) {coeffs[position] = valeur ; }
Matrice& operator= (const Matrice& m) {
if(coeffs != m.coeffs) {
delete [] coeffs ;
dim = m.dim ;
coeffs = new double[m.dim*m.dim] ;
for(int i=0; i<m.dim*m.dim ; i++) {
coeffs[i] = m.coeffs[i] ;
}
}
return *this ;
}
Matrice& operator+=(const Matrice& m) {
for(int i=0; i<dim*dim; i++) {
coeffs[i] += m.coeffs[i] ;
}
return *this ;
}
Matrice&operator+ (const Matrice& m)
{
for(int i=0; i<dim*dim; i++) {
coeffs[i] = coeffs[i] + m.coeffs[i] ;
}
return *this ;
}
double* Coefficients() {return coeffs ;}
void Afficher() {
for(int i=0; i<dim*dim; i++) {
if (i%dim == 0) {cout << endl ; }
cout << coeffs[i] << " " ;
}
cout << endl ;
}
};
#endif /* Matrice_hpp */
不要無故使用指針和'new'。 – juanchopanza
你的重載是'Matrice',而不是'Matrice *'。 – Barmar
不要使用'new' _at all_ –