题目:
http://cxsjsxmooc.openjudge.cn/2021t3springall2/032/
分析:
这个模版真的不难,就是写构造函数,模版类和类的写法基本一致。但这题犯了混,本地没事,提交就Runtime Error,检查了好多遍后才发现。。。有兴趣的话分析一下代码哈,看为什么,也算巩固以下。
参考代码:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
template <class T>
class myclass {
// 在此处补充你的代码
private:
T * p;
int size;
public:
myclass(const T * line,int len) {
size = len;
p = new T[size + 1];
//p = new T(size + 1);
for (int i = 0; i < size; i++) {
p[i] = line[i];
}
}
~myclass( ) {
delete [] p;
}
void Show()
{
for( int i = 0;i < size;i ++ ) {
cout << p[i] << ",";
}
cout << endl;
}
};
int a[100];
int main() {
char line[100];
while( cin >> line ) {
myclass<char> obj(line,strlen(line));;
obj.Show();
int n;
cin >> n;
for(int i = 0;i < n; ++i)
cin >> a[i];
myclass<int> obj2(a,n);
obj2.Show();
}
return 0;
}
RunTime Error 揭晓
p = new T[size + 1]; 这是生成一个初始空间大小为size+1的变量数组。
//p = new T(size + 1); 这是生成一个初始值为size+1的变量。。。
注:以上代码虽然通过了OpenJudge的样例测试,但受限于本人水平,如有疏漏,恳请斧正。