C++编程题,急。。。考试啊
发布网友
发布时间:2023-11-03 01:12
我来回答
共1个回答
热心网友
时间:2024-11-30 03:12
#include <iostream>
#include <memory.h>
using namespace std;
class c_string {
typedef unsigned size_t;
friend c_string& contact(c_string &str1, const c_string& str2);
public:
c_string(size_t length = 20) : m_nLength(length) {
m_pStr = new char[m_nLength + 1];
memset(m_pStr, 0, m_nLength + 1);
}
c_string(const char* pStr) {
m_nLength = strlen(pStr);
m_pStr = new char[m_nLength + 1];
memcpy(m_pStr, pStr, m_nLength + 1);
}
c_string(const c_string& cstr) {
m_nLength = cstr.length();
m_pStr = new char[m_nLength + 1];
memcpy(m_pStr, cstr.c_str(), m_nLength + 1);
}
c_string& operator=(const c_string& cstr) {
if (this == &cstr) {
return *this;
}
delete m_pStr;
m_nLength = cstr.length();
m_pStr = new char[m_nLength + 1];
memcpy(m_pStr, cstr.c_str(), m_nLength + 1);
return *this;
}
void print() const {
cout << m_pStr << endl;
}
~c_string() {
if (m_pStr != NULL) {
delete m_pStr;
}
}
size_t length() const {
return m_nLength;
}
const char* c_str() const {
return m_pStr;
}
private:
char * m_pStr;
size_t m_nLength;
};
c_string& contact(c_string &str1, const c_string& str2) {
if (str2.length() == 0) {
return str1;
}
char *tem = new char[str1.m_nLength + str2.m_nLength + 1];
memcpy(tem, str1.m_pStr, str1.m_nLength);
memcpy(tem + str1.m_nLength, str2.m_pStr, str2.m_nLength + 1);
delete str1.m_pStr;
str1.m_pStr = tem;
return str1;
}
int main() {
char str[] = "hello world";
c_string *_str = new c_string(str);
_str->print();
c_string _str2(*_str);
_str2.print();
c_string _str3;
_str3 = *_str;
delete _str;
_str3.print();
c_string _str4(" how are you ?");
contact(_str2, _str4);
_str2.print();
return 0;
}