百度云课堂上的视频课,记下代码,复习用。
首先定义一个类,iotekstring.h
#ifndef IOTEK_STRING_H
#define IOTEK_STRING_H
#include<iostream>
namespace iotek{
class String{
public:
String(const char * = NULL); \\对输入变量进行初始化
~String();
String(const String&);//拷贝构造函数
//String a; a=b
String& operator=(const String&);//赋值运算符
//String a; a = "Hello"
String& operator=(const char*);//赋值运算符
inline const char* data() const
{
return m_data;
}
private:
char *m_data;
};
}
#endif**
对成员函数进行定义,iotekstring.cpp
#include "iotekstring.h"
#include <string.h>
#include <iostream>
using namespace::std;
using namespace::iotek;
namespace iotek{
String::String(const char* str)
{
if (NULL == str){
m_data = new char[1];
*m_data = '\0';
}
else{
int length = strlen(str);
m_data = new char[length + 1];
strcpy_s(m_data, length+1, str);
}
}
String::~String()
{
delete[] m_data;
}
String::String(const String &other)
{
//深拷贝
int length = strlen(other.m_data);
m_data = new char[length + 1];
strcpy_s(m_data, length+1, other.m_data);
}
//赋值运算符
String & String::operator=(const String &other)
{
if (this == &other){
return *this;
}
delete[] m_data;
int length = strlen(other.m_data);
m_data = new char[length + 1];
strcpy_s(m_data, length+1, other.m_data);
return *this;
}
String & String::operator=(const char* other)
{
delete[] m_data;
if (other == NULL){
m_data = new char[1];
*m_data = '\0';
}
else{
int length = strlen(other);
m_data = new char[length + 1];
strcpy_s(m_data, length+1, other);
}
return *this;
}
}//end of iotek
主函数,main.cpp
#include "iotekstring.h"
#include <iostream>
using namespace::std;
using namespace::iotek;
int main(int argc, char* argv[])
{
String s1("hello");
String s2 = s1; //调用拷贝构造函数
String s3 = "world";
s3 = s1; //调用赋值运算符
s3 = "world";
cout << "s3 = " << s3.data() << endl;
return 0;
}