一:类的三个基本原则
class RuleOfThree {
public:
RuleOfThree(const char* arg) : cstring(new char[std::strlen(arg) + 1])
{
std::strcpy(cstring, arg);
}
~RuleOfThree() { delete[] cstring; }
RuleOfThree(const RuleOfThree& other) {
cstring = new char[std::strlen(other.cstring) + 1];
std::strcpy(cstring, other.cstring);
}
RuleOfThree& operator=(const RuleOfThree& other) {
char* tmp_cstring = new char[std::strlen(other.cstring) + 1];
std::strcpy(tmp_cstring, other.cstring);
delete[] cstring;
cstring = tmp_cstring;
return *this;
}
private:
char* cstring;
};
1.1 用法
RuleOfThree rule("this"); // 构造函数
RuleOfThree rule2(rule); // 拷贝构造函数