So this is my first attempt to write a program using classes in c++. As an exercise, I'm trying to create a 2d-array class that can do certain things. This is a part of the code in the main.cpp that my class has to be able to run.
int main()
{
array2d<double> ar(2,2);
ar(1,1) = 1;
ar(0,0) = 2;
ar(0,1) = 3;
ar(1,0) = 4;
auto X{ar};
array2d<double> c(2,2);
c = ar;
c.diagonal(1) = 5; //c(1,1) = 5
}
And this is my code. I'm getting an error in the diagonal function "error: lvalue required as left operand of assignment". I can't figure out what I should do. The purpose of this function is to assign values in the diagonal elements of the array.
template<typename T>
class array2d
{
private:
int n,m;
vector<T> vec;
public:
array2d(int M, int N)
: n{N}, m{M}
{
vector<T> vec1(n*m);
vec = vec1;
}
array2d(array2d<T> &arr)
: n{arr.N()} , m{arr.M()}
{
vec = arr.V();
}
array2d &operator=(array2d<T> & arr){
vec = arr.V();
return *this;
}
T &operator()(int i,int j)
{
auto it = vec.begin();
it += i*n+j;
return *it;
}
T diagonal(int a)
{
auto x= *this;
return x(a,a);
}
int M (){return m;}
int N (){return n;}
vector<T> V(){return vec;}
};
Aucun commentaire:
Enregistrer un commentaire