三规则。复制构造函数,赋值运算符实现

时间:2013-04-23 06:36:19

标签: c++ destructor copy-constructor assignment-operator rule-of-three

三法则。复制构造函数,分配操作员实现

#include <iostream>
using namespace std;

class IntPart
{
public:
 IntPart(); // default constructor
 IntPart(int n); 

private:
 unsigned int* Counts;
 unsigned int numParts;
 unsigned int size;
};

IntPart::IntPart()
{
 Counts = new int[101] (); // allocate all to 0s
 numParts = 0;
}

IntPart::IntPart(int n)
{
 Counts = new int[n+1] (); // allocate all to 0s
 Counts[n] = 1;
 numParts = 1;
}

int main ()
{
 IntPart ip2(200);
 IntPart ip3(100);

 IntPart ip(ip2); // call default and copy constructor?

 IntPart ip4; // call default constructor
 ip4 = ip3;

 system("pause"); return 0;
}

显然,这需要有三个规则。 你能帮我定一下吗?

Q0。

IntPart ip(ip2);

这个创建ip对象是否调用默认构造函数 之后,调用复制构造函数? 我是对的吗?

Q1。定义析构函数。

IntPart::~IntPart()
{ delete [] Counts; }

是正确的吗?

Q2。定义复制构造函数。

IntPart::IntPart(const IntPart& a)
{ // how do I do this? I need to find the length... size.... could anybody can do this?
}

Q3。定义赋值运算符。

IntPart& IntPart::operator= (const IntPart& a)
{
  if ( right != a)
  {
    // Anybody has any idea about how to implement this?
  }
  return *this;
}

谢谢, 我很感激!

1 个答案:

答案 0 :(得分:3)

Q0。不,这只调用复制构造函数。这是一个非常大的误解,对象只能构建一次

Q1。那是对的

Q2。据推测,您打算将数组大小存储在size中。 E.g。

IntPart::IntPart()
{
    Counts = new int[101] (); // allocate all to 0s
    numParts = 0;
    size = 101; // save array size
}

如果不在某处存储数组大小,则无法编写复制构造函数。

Q3。我会查找copy and swap成语。这允许您使用复制构造函数编写赋值运算符。