【发布时间】:2021-07-12 11:54:32
【问题描述】:
在下面的代码中,我创建了一个模板类,它在主函数中初始化,我正在尝试分配char*,如下所示,但它不起作用。我认为问题出在我在 Proxy 类中定义的分配运算符函数中,但我无法弄清楚
#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";
}
我收到以下错误;
我已经尝试将赋值运算符函数中的参数设置为const,我还尝试将隐式类型转换为T,但没有任何效果
【问题讨论】:
-
“尝试设置
const参数”是什么意思? -
void operator=(const T x) const { a.p[i] = x; }
-
不,你应该将模板参数设为
const char *。 -
Vector<const char *> sv1(2);-- 其中指定模板参数为const char *的部分不清楚? -
没有。
"literal strings"是const char *s。 C++ 不能以任何其他方式工作。
标签: c++ typecast-operator