#include <iostream>
using namespace std;
class String
{
public:
String(char const *chars = "");
String &operator=(String const &);
void print(); // 将输入的字符显示出来,
private:
char *ptrChars;
};
void String::print() // 这个是显示的定义,
{
cout << ptrChars << endl;
}
String &String::operator=(String const &str)
{
if (strlen(ptrChars) != strlen(str.ptrChars)) // strlen是一个计数的,
{
char *ptrHold = new char[strlen(str.ptrChars) + 1];
delete[] ptrChars;
ptrChars = ptrHold;
}
std::strcpy(ptrChars, str.ptrChars);
return *this;
}
String::String(char const *chars)
{
chars = chars ? chars : "";
ptrChars = new char[std::strlen(chars) + 1];
std::strcpy(ptrChars, chars); // strcpy 是复制,将chars的值复制到ptrChars中,
}
int main()
{
String s("xiao");
String s2("cui");
s.print();
s2.print();
s2 = s; // 赋值操作,
return 0;
}
赋值操作符
最新推荐文章于 2018-04-14 12:59:00 发布