参考:http://coolshell.cn/articles/10478.html
#include <string.h>
#include <vector>
class my_string
{
public:
my_string():m_str(new char[1]) {m_str[0] = '\0';}
my_string(const char* pch):m_str(new char[strlen(pch) + 1] ) { strcpy(m_str, pch); }
my_string(const my_string &str):m_str(new char[ str.size() + 1 ] ) { strcpy(m_str, str.c_str()); }
my_string operator=(const my_string &str)
{
printf("Call = fun!\n");
delete []m_str;
m_str = new char[ str.size() + 1 ];
strcpy(m_str, str.c_str());
return *this;
}
char &operator[](const int pos)
{
printf("Call not const [] fun\n");
return m_str[pos];
}
const char &operator[](const int pos) const
{
printf("Call const [] fun\n");
return m_str[pos];
}
char* operator&(const int pos){return &m_str[pos];}
~my_string(){ delete []m_str;}
unsigned int size() const {return strlen(m_str); }
const char* c_str() const { return m_str;}
private:
char *m_str;
};
void foo(my_string x)
{
}
void bar(const my_string& x)
{
}
my_string baz()
{
my_string ret("world");
return ret;
}
my_string str1("0123456789qqqqq");
my_string str2("0123456789");
void test_referenc_ret()
{
str2 = str1;
}
int main()
{
my_string str1("0123456789qqqqq");
printf("str1[5] is %c\n", str1[5]);
str1[5] = 'a';
printf("str1[5] is %c\n", str1[5]);
const my_string str2("0123456789");
printf("str2[5] is %c\n", str2[5]);
my_string str3;
str3 = str1;
printf("str1 is %s, str3 is %s\n", str1.c_str(), str3.c_str());
/*
my_string s0;
my_string s1("hello");
my_string s2(s0);
my_string s3 = s1;
s2 = s1;
foo(s1);
bar(s1);
foo("temporary");
bar("temporary");
my_string s4 = baz();
std::vector<my_string> svec;
svec.push_back(s0);
svec.push_back(s1);
svec.push_back(baz());
svec.push_back("good job");
*/
}