#include <iostream>
#include <cstring>
using namespace std;
class mString
{
public:
mString(const char * buf)//有参构造函数
:m_buf(strcpy(new char[strlen(buf) + 1 ],buf) )
{
}
mString(const mString& that)//拷贝构造函数
:m_buf(strcpy(new char[strlen(that.m_buf)+1],that.m_buf) )
{
}
virtual ~mString()
{
if(m_buf)
{
delete m_buf;
}
}
const mString& operator=(const mString& that)//拷贝赋值
{
if(&that != this)
{
if(m_buf) delete[] m_buf;
m_buf = strcpy(new char[strlen(that.m_buf)+1],that.m_buf);
}
return *this;
}
const mString& operator=(const char * buf)//拷贝赋值
{
delete[] m_buf;
m_buf = new char[strlen(buf)+1];
return *this;
}
friend const mString operator+(const mString& left,const mString& right)//重载+(友元函数 非成员函数版本)
{
char * tbuf = new char[ strlen(left.m_buf)+strlen(right.m_buf)+1 ];
mString tt(strcat(strcpy(tbuf,left.m_buf),right.m_buf) ) ;//调用有参构造
delete[] tbuf;
return tt;
}
const char* mc_str()const
{
return m_buf;
}
void print()const
{
cout<<mc_str()<<endl;
}
private:
char * m_buf;
};
int main()
{
mString str1("aaaa");//有参构造
str1.print();
cout<<"----------"<<endl;
mString str2="bbbb";//拷贝赋值
str2.print();
cout<<"----------"<<endl;
mString str3= str1+str2;//重载+
str3.print();
cout<<"----------"<<endl;
mString str4(str3);//拷贝构造
str4.print();
cout<<"----------"<<endl;
const char* (mString::*pfn)()const = &mString::mc_str;//常函数也要加上标识
cout<<(str1.*pfn)()<<endl;
cout<<"----------"<<endl;
void (mString::*pfn2)()const = &mString::print;
mString *pStr =&str2;
(pStr->*pfn2)();
getchar();
return 0;
}
原文:http://my.oschina.net/mlgb/blog/361724