032:这个模板并不难

题目:

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的样例测试,但受限于本人水平,如有疏漏,恳请斧正。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值