c++构造函数(普通构造函数,拷贝构造函数,复制构造函数,析构函数)

以下为普通构造函数,拷贝构造函数,复制构造函数,析构函数;
当数据类型有指针时,要小心内存泄漏;
 
#include<iostream>
#include<string.h>
using namespace std;
class String
{
   public:
      String(const char *str = NULL);
      String(const String &other);
      ~String(void);
      String& operator =(const String &other);
   public:
      char *m_data;
};
String::~String(void)
{
   delete []m_data;
   printf("析构函数,释放内存\n");
}
String::String(const char *str)
{
   if(str == NULL)
   {
      m_data = new char[1];
      *m_data = '\0';
  
      printf("普通构造函数,入参为空");
   }
   else
   {
      m_data = new char[strlen(str) + 1];
      strcpy(m_data, str);
      printf("普通构造函数,入参有值");
   }
}
String::String(const String &other)
{
   m_data = new char[strlen(other.m_data) + 1];
   strcpy(m_data, other.m_data);
   printf("拷贝构造函数");
}
String& String::operator =(const String &other)
{
   if(this == &other)
   {
      printf("赋值函数,相等");
      return *this;
   }
 
   delete []m_data;               //防止内存泄漏
 
   m_data = new char[strlen(other.m_data) + 1];
   strcpy(m_data, other.m_data);
   printf("赋值函数,不相等");
   return *this;
}
 
int main()
{
   String a;
   cout << "1: " << a.m_data << endl;
 
   String b(" ");
   cout << "2: " << b.m_data << endl;
 
   String c("abc");
   cout << "3: " << c.m_data << endl;
 
   String d = c;
   cout << "4: " << d.m_data << endl;
  
   String e(d);
   cout << "5: " << e.m_data << endl;
 
   String f;
   f = d;
   cout << "6: " << f.m_data << endl;
   f = f;
   cout << "7: " << f.m_data << endl;
  
   return 0;
}
 
偷懒的办法处理拷贝构造函数与赋值函数:
如果我们实在不想编写拷贝构造函数和赋值函数,又不允许别人使用编译器生成的
缺省函数,怎么办?
偷懒的办法是:只需将拷贝构造函数和赋值函数声明为私有函数,不用编写代码。
例如:
class A
{ …
  private:
  A(const A &a); // 私有的拷贝构造函数
  A & operate=(const A &a); // 私有的赋值函数
};
 
如果有人试图编写如下程序:
A b(a); // 调用了私有的拷贝构造函数
b = a; // 调用了私有的赋值函数
 
编译器将指出错误,因为外界不可以操作 A 的私有函数。
 
 

猜你喜欢

转载自www.cnblogs.com/yangyi54920/p/11900289.html