Dear friends:
I write a vector class "vec" based on the template, i am confused greatly by the "const" keyword appeared at the left most when the = operator is defined.
const vec& operator=(const vec & a)
Could you please tell me what is the function of this "const". I known that when the member function operates on some const variables, it should be declared as const also, but the const keyword is placed at the end behind the function declaration. When i move this const to the end, the codeblock gives me the following error:
f:\cblockmain\obj\vector.h|34|error C2440: 'return' : cannot convert from 'const vec<T,N>' to 'vec<T,N> &'|
f:\cblockmain\obj\vector.h|36|error C2166: l-value specifies const object|
f:\cblockmain\obj\vector.h|34|error C2440: 'return' : cannot convert from 'const vec<T,N>' to 'vec<T,N> &'|
f:\cblockmain\obj\vector.h|37|error C2440: 'return' : cannot convert from 'const vec<T,N>' to 'vec<T,N> &'|
||=== Build finished: 3 errors, 0 warnings ===|
The header file are as follows:
#ifndef VECTOR_H_INCLUDED
#define VECTOR_H_INCLUDED
#include<iostream>
using namespace std;
template<class T, int N> class vec
{
private:
T component[N];
public:
vec(){}
vec( const T& a)
{
for(int i=0; i<N; i++) component[i]=a;
}
vec( const T& a, int n, char*)
{
for(int i=0; i<N; i++) component[i]=0;
component[n]=a;
}
vec(const vec<T,N>& v)
{
for(int i=0; i<N; i++) component[i]=v.component[i];
}
const vec& operator=(const vec & a)
{
if(this==&a)
return *this;
for(int i=0; i<N; i++) component[i]=a.component[i];
return *this;
}
const vec& operator=(const T & a)
{
for(int i=0; i<N; i++) component[i]=a;
return *this;
}
~vec()
{
}
T& operator[] (int i) const
{
return component[i];
}
void show()
{
for(int i=0; i<N; i++)
{
cout<<component[i]<<endl;
}
}
};
#endif // VECTOR_H_INCLUDED
This is the main file:
#include <iostream>
#include "obj/vector.h"
using namespace std;
int main()
{
vec<double,4> V(1.0,3,"l love you");
V.show();
vec<double,4> V2(V);
vec<double,4> V3;
V3=V2;
V3.show();
return 0;
}