类模板编译报错
为啥报错?template <class T>class Vector
{
private:
int len;
T items;
public:
Vector(int size = 10):len(size)
{
items = new T;
}
~Vector()
{
delete[] items;
items = NULL;
};
void resize(int size)
{
if (size <= len)
{
return;
}
T* tmp = new T;
for (size_t i = 0; i <len ; i++)
{
tmp = items;
}
delete[] items;
items = tmp;
tmp = NULL;
len = size;
}
int size()
{
return len;
}
T& operator[](int i)
{
if (i > len)
{
resize(i + 1);
}
return items;
}
const T& operator[](int i)const
{
return items;
}
};
int main()
{
Vector<std::string> a(10);
a = "哈哈";
a = "哈哈1";
a = "哈哈2";
a = "哈哈3";
a = "哈哈4";
for (size_t i = 0; i < a.size(); i++)
{
std::cout << a;
}
}生成开始于 17:50...
1>------ 已启动生成: 项目: 模板示例:数组, 配置: Debug x64 ------
1>模板示例:数组.cpp
1>C:\Users\Administrator\source\repos\模板示例:数组\模板示例:数组\模板示例:数组.cpp(69,23): error C2440: “return”: 无法从“char”转换为“T &”
1>C:\Users\Administrator\source\repos\模板示例:数组\模板示例:数组\模板示例:数组.cpp(69,23): error C2440: with
1>C:\Users\Administrator\source\repos\模板示例:数组\模板示例:数组\模板示例:数组.cpp(69,23): error C2440: [
1>C:\Users\Administrator\source\repos\模板示例:数组\模板示例:数组\模板示例:数组.cpp(69,23): error C2440: T=std::string
1>C:\Users\Administrator\source\repos\模板示例:数组\模板示例:数组\模板示例:数组.cpp(69,23): error C2440: ]
1>已完成生成项目“模板示例:数组.vcxproj”的操作 - 失败。
========== 生成: 0 成功,1 失败,0 最新,0 已跳过 ==========
========== 生成 于 17:50 完成,耗时 01.179 秒 ==========
#include <iostream>
template<class T> class Vector {
private:
size_t len;
T *items;
public:
Vector(size_t size = 10): len(size), items(new T) {}
~Vector() {delete[] items;};
void resize(size_t size) {
if(size <= len) return;
T *tmp = new T;
for(size_t i = 0; i < len; i++) {
tmp = items;
}
delete[] items;
items = tmp;
len = size;
}
size_t size() {return len;}
T &operator[](size_t i) {
if(i > len) resize(i + 1);
return items;
}
const T &operator[](size_t i) const {return items;}
};
int main() {
Vector<std::string> a(10);
a = "哈哈";
a = "哈哈1";
a = "哈哈2";
a = "哈哈3";
a = "哈哈4";
for(size_t i = 0; i < a.size(); i++) {
std::cout << a;
}
std::cout << std::endl;
}
页:
[1]