Add operator with assignment operator

I overloaded =,+= and + operator for a custom template class. Here are my codes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
template <class vtype>
inline matrix<vtype>& matrix<vtype>::operator=(matrix<vtype> &rhs){
   int i,j;
   
   if (this != &rhs){
        mat.assign(rhs.height(),VECTOR_TY(rhs.width(),rhs[0][0]));
	for (i=0;i<rhs.height();i++)
	  for (j=0;j<rhs.width();j++)
	     mat[i][j]=rhs.mat[i][j];
   }
   return *this;
}

template <class vtype>
inline matrix<vtype>& matrix<vtype>::operator+=(matrix<vtype> &rhs){
   int i,j;
   
   if (height()==rhs.height() && width()==rhs.width()){
	for (i=0;i<rhs.height();i++)
	  for (j=0;j<rhs.width();j++)
	     mat[i][j]=mat[i][j]+rhs.mat[i][j];
        return *this;
   }
   else{
        std::cout<<"Matrix sizes don't match\n";
	exit(0);
   } 
}

template <class vtype>
inline const matrix<vtype> matrix<vtype>::operator+(matrix<vtype> &rhs){
   if (height()==rhs.height() && width()==rhs.width()){
        matrix<vtype> result;
        result = *this;
        result += rhs;
        return result;
   }
   else{
        std::cout<<"Matrix sizes don't match\n";
	exit(0);
   } 
}


The operator= and operator+= work fine but the tried to use operator+,
e.g. A=M+N; where A,M and N are the object of the template class.
The compiler complaints


main.cpp:20: error: no match for ‘operator=’ in ‘A = matrix<vtype>::operator+
(matrix<vtype>&) [with vtype = double](((matrix<double>&)(& M)))’
matrix.hpp:42: note: candidates are: matrix<vtype>& matrix<vtype>::operator=
(matrix<vtype>&) [with vtype = double]


The complier said no match for 'operator=' but clearly i defined it and the
input and output type match.
Anyone know what was wrong? Thanks
Please post a complete main function that shows how the class is used. By the way why are you returning a const object by value? I can understand operator+ being const to not modify the object but you return a temp by value. Why is the const associated with the return value?
Last edited on
I tried to duplicate with my own simple example using global functions but could not. This compiles fine for me. I'm not sure what is wrong with your code without seeing a more complete example.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <vector>
#include <algorithm>

template <class T>
std::vector<T> copyfunction(const std::vector<T>& rhs)
{
    std::vector<T> value;
    value = rhs;
    return value;
}

int main()
{
    std::vector<int> MyArray(20);
    std::generate(MyArray.begin(), MyArray.end(), rand);
    std::vector<int> MyOtherArray(copyfunction(MyArray));

    return 0;
}
Topic archived. No new replies allowed.