拷贝构造函数和赋值构造函数声明为私有

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zxc024000/article/details/80216823

拷贝构造函数和赋值构造函数声明为私有

  • 默认情况,编译器以“位拷贝”的方式自动生成缺省的构造函数和赋值函数。若类中有指针变量,那么缺省的构造函数会出现错误。
  • 拷贝构造函数在对象创建时被调用
  • 赋值构造函数只能被已存在的对象调用。
String a("hello");
String b("world");
//拷贝构造函数
String c = a;
//赋值构造函数
c= b;
  • 拷贝构造函数
String::String(const String &other)
{
 int length = strlen(other.m_data);
 m_data = new char[length+1];
 strcpy(m_data, other.m_data);
}
  • 赋值构造函数
String & String::operate =(const String &other)
{
 if(this == &other)
 return *this;
 delete [] m_data;
 int length = strlen(other.m_data);
 m_data = new char[length+1];
  strcpy(m_data, other.m_data);
 return *this;
}
  • 如果不想编写拷贝构造、赋值构造函数,又不允许别人使用,可以将拷贝构造函数和赋值构造函数声明为私有函数
class A
{ 
 private:
 A(const A &a); // 私有的拷贝构造函数
 A & operate =(const A &a); // 私有的赋值函数
};
A b(a); //错误,不能调用私有的拷贝构造函数
b = a; //错误,不能调用私有的赋值构造函数



class B
{
    public:
       B(A& a)
       : m_a(a) // 错误,不允许调用拷贝构造函数
       {}
    private:
      A m_a; // 错误
}

class C
{
    public:
       C(A& a)
       : m_a(a) // 正确,只是引用,并没有拷贝
       {}
    private:
      A& m_a; // 正确
}

相关系列

猜你喜欢

转载自blog.csdn.net/zxc024000/article/details/80216823
今日推荐