Chinaunix首页 | 论坛 | 博客
  • 博客访问: 628105
  • 博文数量: 227
  • 博客积分: 8017
  • 博客等级: 中将
  • 技术积分: 2069
  • 用 户 组: 普通用户
  • 注册时间: 2007-12-08 22:50
文章分类

全部博文(227)

文章存档

2011年(10)

2010年(55)

2009年(28)

2008年(134)

我的朋友

分类:

2009-10-05 09:43:11

编写类String的构造函数、析构函数和赋值函数


#include <iostream>
using namespace std;

class String
{
public:
    String(char *str=NULL);
    String(const String &str);
    ~String();
    friend ostream& operator<<(ostream &out, const String &obj);
    String& operator=(const String &other);
private:
    char *buf;
};


String::String(char *str)
{
    int len = strlen(str);
    if (str==NULL){
        buf = new char[1];
        buf[0] = '\0';
    }
    if (len > 0){
        buf = new char[len];
        strcpy(buf, str);
    }
}


String::String(const String &str)
{
    int len = strlen(str.buf);
    if (len > 0){
        buf = new char[len];
        strcpy(this->buf, str.buf);
    }
}


String::~String()
{
    delete []buf;
}

String & String::operator=(const String &other)
{
    if (this == &other)
        return *this;
    this->buf = new char[strlen(other.buf)];
    strcpy(this->buf, other.buf);

    return *this;
}


ostream & operator<<(ostream &out, const String &str)
{
    out <<str.buf<<endl;
    return out;
}

int main(void)
{
    String s1("hello,world!");
    String s2 = s1;
    //delete s1;

    cout << "s1 = " << s1;
    cout << "s2 = " << s2;
    
    String *ps1 = new String("test_copy");
    String s3 = *ps1;
    delete ps1;
    cout << "s3= " << s3;
}



面试题目:
1. 删除文件的第3行:
  sed '3d' input.txt > output.txt
2. 打印文件的第100行
  sed -n '100p' input.txt
3. 删除当前目及子目录下的得所有的以txt结尾的文件:
  find . -name '*.txt' -type f -exec rm -f {} \;


阅读(1047) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~