异想天开

What's the true meaning of light, Could you tell me why

字符串的类

日期:2015-08-18 16:07:13
  
最后更新日期:2015-08-18 16:11:12
写一个c++的CString类,要求有构造函数,默认构造函数,拷贝函数,赋值函数,析构函数。
这道题为某厂的面试题,基础的一道,其中也犯了一些问题。赋值操作符函数编写。
CString类头文件
[code lang="cpp"]
//CString.h
#ifndef __CSTRING_H__
#define __CSTRING_H__
#include <string.h>

class CString{
public:
CString():m_base(0),m_len(0){}
CString(const char *str)
{
if (NULL == str)
{
m_base = NULL;
m_len = 0;
return ;
}

m_len = strlen(str);
m_base = new char[m_len+1];
if (m_base)
{
strncpy(m_base,str,m_len);
m_base[m_len] = 0;
}
}

CString(CString &str)
{
if (NULL == str.c_str() || 0 == str.len())
{
m_base = NULL;
m_len = 0;
return ;
}

m_len = strlen(str.c_str());
m_base = new char[m_len+1];
if (m_base)
{
strncpy(m_base,str.c_str(),str.len());
}
}

~CString(){ delete []m_base; }
CString & operator = (const CString &);
const char *c_str() const { return m_base;}
const int len() const { return m_len;}
private:
void swap(CString &str);
char *m_base;
int m_len;
};


#endif
[/code]

CString实现
[code lang="cpp"]
//CString.cpp
#include<string.h>
#include "CString.h"

void CString::swap(CString &str)
{
int tmp_len = m_len;
m_len = str.m_len;
str.m_len = tmp_len;
char *tmp_base = m_base;
m_base = str.m_base;
str.m_base = tmp_base;
}

CString & CString::operator =(const CString &str)
{
if (this == &str)
{
return *this;
}

CString tmp(str.c_str());
swap(tmp);

return *this;
}
[/code]

单元测试
[code lang="cpp"]
//CString_unit.cpp
#include "CString.h"
#include "gtest/gtest.h"
#include<string.h>

TEST(CString,defconstructor)
{
const CString s;
EXPECT_STREQ(NULL, s.c_str());
EXPECT_EQ(0u, s.len());
}

TEST(CString,constructor)
{
const char *p = "hello world";
const CString s(p);
EXPECT_STREQ(p, s.c_str());
EXPECT_EQ(strlen(p), s.len());
}

TEST(CString,assign1)
{
const char *p = "hello world";
CString b(p);
CString a;
const char *abase = a.c_str();
const char *bbase = b.c_str();
int alen = a.len();
int blen = b.len();
a = b;
EXPECT_EQ(bbase,b.c_str());
EXPECT_EQ(blen,b.len());
EXPECT_STREQ(p, a.c_str());
EXPECT_EQ(strlen(p), a.len());
}

TEST(CString,assign2)
{
const char *p = "hello world";
CString a(p);
const char *base = a.c_str();
a = a;
EXPECT_STREQ(p, a.c_str());
EXPECT_EQ(strlen(p), a.len());
EXPECT_EQ(base,a.c_str());
}

TEST(CString,assign3)
{
const char *p = "hello world";
CString b(p);
CString a("test");
const char *bbase = b.c_str();
int blen = b.len();
a = b;
EXPECT_EQ(bbase,b.c_str());
EXPECT_EQ(blen,b.len());
EXPECT_STREQ(p, a.c_str());
EXPECT_EQ(strlen(p), a.len());
}
[/code]