拷贝构造函数与赋值
拷贝构造函数
String(const String& other) =delete;
赋值
void operator=(const String& )=delete;
只要产生新对象其实就是调用了拷贝构造函数
class String {
private:
char *m_Buffer;
unsigned int m_Size;
public:
String(const char *string) {
m_Size = strlen(string);
m_Buffer = new char[m_Size + 1];
memcpy(m_Buffer, string, m_Size);
m_Buffer[m_Size] = 0;
}
String() {
}
String(const String &other)
: m_Size(other.m_Size) {
m_Buffer = new char[m_Size + 1];
memcpy(m_Buffer, other.m_Buffer, m_Size + 1);
m_Buffer[m_Size] = 0;
}
String &operator=(const String &other) {
m_Size = other.m_Size;
m_Buffer = new char[m_Size + 1];
memcpy(m_Buffer, other.m_Buffer, m_Size + 1);
return *this;
}
~String() {
std::cout << "Dleteted String: " << m_Buffer << std::endl;
delete[] m_Buffer;
}
char &operator[](unsigned int index) const {
return m_Buffer[index];
}
friend std::ostream &operator<<(std::ostream &stream, const String &string);
};
std::ostream &operator<<(std::ostream &stream, const String &string) {
stream << string.m_Buffer;
return stream;
}
int main() {
String string("12345");
String second;
second = string;
second[2] = 'a';
std::cout << string << std::endl;
std::cout << second << std::endl;
return 0;
}