实现构造、拷贝构造、析构、赋值以及输出操作
String.h
#ifndef _String_//防卫式声明
#define _String_
#pragma warning(disable : 4996)//忽略4996警告
#include<iostream>
using namespace std;
class String
{
public:
String(const char* s=0);//构造,一定要加上const,才能使常量字符进行初始化
String(const String& s);//拷贝构造
String& operator=(const String& s);//重载赋值操作
~String();//析构
private:
char* str;
friend ostream& operator<<(ostream& os, const String& s);//友元
};
ostream& operator<<(ostream& os, const String& s);//重载输出
#endif _String_
String.cpp
#include "String.h"
String::String(const char* s)
{
if (s)
{
this->str = new char[strlen(s) + 1];
strcpy(this->str, s);
}
else
{
this->str = new char[1];
*this->str = '\0';
}
}
String::String(const String& s)//声明和定义处只能一处有默认参数
{
this->str = new char[strlen(s.str) + 1];
strcpy(this->str, s.str);
}
String& String::operator=(const String& s)
{
if (this == &s)//自身赋给自身直接返回(必须)
{
return *this;
}
delete[]this->str;//先释放已有空间
this->str = new char[strlen(s.str) + 1];//重新开辟空间
strcpy(this->str, s.str);
return *this;
}
String::~String()
{
delete[]str;
}
ostream& operator<<(ostream& os, const String& s)//只能写为全局函数
{
return (os << s.str);
}
测试.cpp
#include"String.h"
int main()
{
String s;
String s1("hello,world");
cout << s1 << endl;
s = s1;
cout << s << endl;
String s3(s1);
cout << s3;
}
含有指针的类基本上需要实现拷贝构造函数、赋值函数以及析构函数(three tree)
array new 要对应array delete