#ifndef _SD_STRING_H_ #define _SD_STRING_H_ #include <iostream> using namespace std; class SDString { public: SDString(); SDString(char *str); SDString(const SDString &str); ~SDString(); SDString& operator=(const SDString &str); friend ostream& operator <<(ostream& os, const SDString &str) { return os << str.m_str << endl; } private: char *m_str; }; #endif /*_SD_STRING_H_*/ #include "SDstring.h" #include <cstdlib> #include <cstring> using namespace std; SDString::SDString() { m_str = new char[1]; *m_str = '/0'; } SDString::SDString(char *str) { if(str == NULL) { SDString(); return; } m_str = new char[strlen(str) + 1]; strcpy(m_str, str); } SDString::SDString(const SDString &str) { m_str = new char[strlen(str.m_str) + 1]; strcpy(m_str, str.m_str); } SDString::~SDString() { if(m_str != NULL) delete[] m_str; m_str = NULL; } SDString& SDString::operator=(const SDString &str) { if(this == &str) return *this; delete[] m_str; m_str = new char[strlen(str.m_str) + 1]; strcpy(m_str, str.m_str); } #include "SDstring.h" #include <iostream> #include <cstdlib> using namespace std; int main(int argc, char *argv[]) { SDString str1(); cout << str1; SDString str2("xyu"); cout << str2; SDString str3(str2); cout << str3; system("PAUSE"); return EXIT_SUCCESS; } 这个例子还有个问题, 不知咋回事... 还有要注意的是, 友元函数的实现最好放到类定义的里面, 否则在编译时可能会出现不能够访问类私有成员函数的错误, 记得之前遇到过, 大概是编译器的问题...