In the following code I made a template class, Its initialized in main function and I'm trying to assign char*
as you can see below but It isn't working. I think the issue is in assign operator function I defined in Proxy class but I can't figure it out
#include <iostream>
using namespace std;
template <class T>
class Vector {
public:
T *p;
Vector(int size) {
p = new T[size];
}
class Proxy {
Vector &a;
int i;
public:
Proxy(Vector &a, int i) : a(a), i(i) {
}
void operator=(const T x) {
a.p[i] = x;
}
};
Proxy operator[](int i) {
return Proxy(*this, i);
}
};
int main() {
Vector<char *> sv1(2);
sv1[0] = "John";
sv1[1] = "Doe";
}
I'm getting following error;
I already tried setting parameter in assignment operator function to const
, I also tried implicitly typecasting to T
nothing has worked
Try this:
Your code will work with any basic type, (
int
,char
,double
) and pointers, but not, for example, with this:Firstly, the Vector points to a
char*
, not a string literal (const char*
). You'd have to cast it using a C-style cast or aconst_cast
. Example:A string literal is always a
const char*
in C++.