码迷,mamicode.com
首页 > 编程语言 > 详细

C++笔试题经典的两个

时间:2015-07-10 16:47:32      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:笔试题

//实现一个自己版本的string。
#include <iostream>
#include <string.h>
using namespace std;

class String
{
public:
    String(const char *s = "")
    {
        str = new char[strlen(s) + 1];
        copy(str,s);
    }
    ~String()
    {
        if (str != NULL)
        {
            delete[]str;
            str = NULL; 
        }
    }
    String(const String &s)
    {
        str = new char[strlen(s.str) + 1];
        copy(str,s.str);
    }
    String& operator=(const String &s)
    {
        String sp(s.str);
        if (this != &s)
        {
            char *temp = str;
            str = sp.str;
            sp.str = temp;
        }
        return *this;
    }
    void Printf()
    {
        cout << str << endl;
    }
    friend  istream& operator>>(istream &is,String& s)
    {
        char *str = new char[30];
        is >> str;
        String temp(str);
        s = temp;
        return is;
    }
    friend ostream& operator << (ostream &out, String& s)
    {
        out << s.str;
        return out;
    }
private:
    void copy(char *dist,const char *src)
    {
        strcpy(dist,src);
    }
private:
    char *str;
};
int main()
{
    String s;
    cin >> s;
    cout << s<<endl;
    return 0;
}


#include <iostream>
using namespace std;
//实现一个简单的智能指针。
template<typename Type>
class my_auto
{
public:
    my_auto(Type *p) :ptr(p)
    {
        count = new int[1];
        count[0] = 1;
    }
    my_auto(const my_auto<Type>& ma)
    {
        ptr = ma.ptr;
        count = ma.count;
        count[0]++;
    }
    my_auto& operator=(const my_auto &ma)
    {
        if (this != &ma)
        {
            this->~my_auto();
            ptr = ma.ptr;
            count = ma.count;
            count[0]++;
        }
        return *this;
    }
    ~my_auto()
    {
        if (count[0]-- == 1)
        {
            cout << "free" << endl;
            delete ptr;
            ptr = NULL;
            delete[]count;
            count = NULL;
        }
    }
    Type& operator*()
    {
        return *ptr;
    }
    Type* operator->()
    {
        return ptr;
    }
private:
    Type *ptr;
    int *count;
};
int main()
{
    my_auto<int> sp(new int(3));
    my_auto<int> sb(sp);
    my_auto<int> sa(new int(100));
    sa = sb;
    //cout << *sp << endl;
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

C++笔试题经典的两个

标签:笔试题

原文地址:http://blog.csdn.net/liuhuiyan_2014/article/details/46830735

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!