I am a c++ beginner and i have trouble compiling the following code
the problem is in the statement T a = s
where s
is a char*
containing abcde
.
The goal here is to declare an object of T
and initializing it with s
.
I also have trouble in this line for(int i = 0; i < a(); i++)
.
I don't know how can i use a constructor or a function named a()
to return the size.
This my code :
#include <iostream>
#include <cassert>
using namespace std;
class T{
int nb ;
char *pc;
public:
T(int);
~T();
T(T&);
char& operator[](int);
T(const char* s){
int n ;
for(int i = 0 ; s[i] != '\0' ;i++ ) n++ ;
nb = n ;
pc= new char[nb];
for(int i=0 ; i < nb ; i++) pc[i] = s[i];
}
};
T::T(int k){
assert(k > 0);
nb = k;
pc = new char[nb];
}
T ::~T(){
if( pc != NULL) delete [] pc;
}
T::T(T& t){
nb=t.nb;
delete[] pc;
pc = new char[nb];
for(int i=0 ; i < nb ; i++) pc[i] = t.pc[i];
}
char& T::operator[](int index){
assert(index >=0 && index <= nb);
return pc[index];
}
int main(){
char* s = "abcde";
T a = s;
for(int i = 0; i < a(); i++)
cout << a[i] << " ";
cout << endl;
T b = a;
b[1] = '*';
b[3] = '*';
for(int i = 0; i < b(); i++)
cout << b[i] << " ";
cout << endl;
return 0;
}
i get the following error :
invalid initialization of non-const reference of type 'T&' from an rvalue of type 'T'|