String类的编写
来源:互联网 发布:怎样进入上层社会 知乎 编辑:程序博客网 时间:2024/06/05 04:17
#include<iostream>
#include<stdlib.h>
using namespace std;
class String
{
{}
String(const char *x) :ptr(new char[strlen(x) + 1])
{
//将x中的字符串拷贝到ptr中
strcpy(ptr,x);
}
String(const String &other)
{
//自己拷贝自己情况
if (this != &other)
{
//拷贝构造不可能出现ptr原来就有指向的情况
ptr = new char[strlen(other.ptr) + 1];
strcpy(ptr, other.ptr);
}
}
String& operator=(const String &other)
{
//自己拷贝自己情况
if (this != &other)
{
//当ptr原来有指向空间时
if (ptr != NULL)
delete []ptr;
ptr = new char[strlen(other.ptr) + 1];
strcpy(ptr, other.ptr);
}
return *this;
}
char* GetString()
{
return ptr;
}
~String()
{
if (ptr != NULL)
delete[]ptr;
}
private:
char *ptr;
};
int main()
{
char *a = "nihao";
char *x;
char *y;
//构造函数测试
String test1;
String test2(a);
x = test1.GetString();
y = test2.GetString();
while (*x != '\0')
cout << *x++;
cout << endl;
while (*y != '\0')
cout << *y++;
cout << endl;
//拷贝构造函数测试
String test3(test2);
char *z = test3.GetString();
while (*z != '\0')
cout << *z++;
cout << endl;
//赋值重载测试
test1 = test2;
x = test1.GetString();
while (*x != '\0')
cout << *x++;
cout << endl;
return 0;
}
#include<stdlib.h>
using namespace std;
class String
{
public:
//当不传值构造时,默认为一个‘\0’
{}
String(const char *x) :ptr(new char[strlen(x) + 1])
{
//将x中的字符串拷贝到ptr中
strcpy(ptr,x);
}
String(const String &other)
{
//自己拷贝自己情况
if (this != &other)
{
//拷贝构造不可能出现ptr原来就有指向的情况
ptr = new char[strlen(other.ptr) + 1];
strcpy(ptr, other.ptr);
}
}
String& operator=(const String &other)
{
//自己拷贝自己情况
if (this != &other)
{
//当ptr原来有指向空间时
if (ptr != NULL)
delete []ptr;
ptr = new char[strlen(other.ptr) + 1];
strcpy(ptr, other.ptr);
}
return *this;
}
char* GetString()
{
return ptr;
}
~String()
{
if (ptr != NULL)
delete[]ptr;
}
private:
char *ptr;
};
int main()
{
char *a = "nihao";
char *x;
char *y;
//构造函数测试
String test1;
String test2(a);
x = test1.GetString();
y = test2.GetString();
while (*x != '\0')
cout << *x++;
cout << endl;
while (*y != '\0')
cout << *y++;
cout << endl;
//拷贝构造函数测试
String test3(test2);
char *z = test3.GetString();
while (*z != '\0')
cout << *z++;
cout << endl;
//赋值重载测试
test1 = test2;
x = test1.GetString();
while (*x != '\0')
cout << *x++;
cout << endl;
return 0;
}
0 0
- String类的编写
- string类的编写
- 编写一个自定义的String类
- C++ String类基本函数的编写
- String的编写
- 编写String类
- 编写类String原型
- 自己编写的string库函数
- 编写类String 的构造函数、析构函数
- Java基础复习:编写简单的String工具类
- 根据C++ Primer 5th编写的自定义String类
- c++之string类编写
- Database的Connection String编写方法
- 126.自己编写String类
- c++常见题目,编写string类
- 编写类String的构造函数、析构函数和赋值函数,已知类String的原型
- 编写类String的构造函数、析构函数和赋值函数,已知类String的原型
- String 类的编写:1.各种运算符的重载 2.用引用计数来实现String类
- 数据类型和运算符(二)
- codeforces 448 B. Suffix Structures
- what happened while start nova compute service
- 面试题3:替换空格和清除空格
- 黑马day16 jquery&基本过滤器
- String类的编写
- CSS布局之各种居中
- NAT/Route/Tunnel三种模式实现代码简介
- 棋盘问题
- Ural 1557 1557. Network Attack
- jquery blockui
- linux小白日记
- spark接hbase遇到版本兼容的问题
- Longest Substring Without Repeating Characters