class CString
{
char m_buff[MAXLENGTH];
public:
CString(); //構造函數1,設置為空字符串
~CString();
friend ostream& operator<<(ostream& Out, const CString& S); //輸出字 符串
char operatorconst;
};
CString::CString()
{
m_buff[0]=NULL;
}
char CString::operatorconst
{
return m_buff[i];
}
ostream& operator<<(ostream& Out, const CString& S)
{
return Out<<S.m_buff<<endl;
}
CString::~CString()
{
delete[] m_buff;
}
void main()
{
CString s1;
cout << s1;
}
這是其中一段
// MyString.cpp : 定義控制台應用程序的入口點。
//
#include "stdafx.h"
#include
#include
class MyString
{
public:
MyString(const char str = NULL);
MyString(const MyString &other);
~MyString(void);
MyString & operator = (const MyString &other);
int OutputStr(void);
private:
char *m_data;
};
MyString::MyString(const char *str)//普通的構造函數
{
if (str == NULL)
{
m_data = new char[1];
*m_data = '/0';
}
else
{
int length = strlen(str);
m_data = new char[length + 1];
strcpy(m_data, str);
}
}
MyString::MyString(const MyString &other)//拷貝構造函數
{
int length = strlen(other.m_data);
m_data = new char[length + 1];
strcpy(m_data, other.m_data);
}
MyString::~MyString(void)
{
delete [] m_data;
}
MyString & MyString::operator = (const MyString &other)//賦值操作
{
if (this == &other)
{
return *this;
}
delete [] m_data;
int length = strlen(other.m_data);
m_data = new char[length + 1];
strcpy(m_data, other.m_data);
return *this;
}
int MyString::OutputStr(void)
{
int length = 0;
length = strlen(m_data);
printf("the output string is : %s", m_data);
return length;
}
int _tmain(int argc, _TCHAR argv[])
{
MyString str("hello, world");//進入普通構造函數
MyString str2 = str;//初始化,進入拷貝構造函數
MyString str3(str);//初始化,進入拷貝構造函數
str2 = str;//賦值,進入賦值操作
str2.OutputStr();
//MyString *str = new MyString("hello, world");//普通構造函數
//MyString *str2 = new MyString(*str);//拷貝構造函數
//*str2 = *str;//賦值操作
//str2->OutputStr();
getchar();
return 0;
}