【问题标题】:Rule of Three. Copy Constructor, Assignment Operator Implementation [closed]三法则。复制构造函数,赋值运算符实现
【发布时间】:2013-04-23 06:36:19
【问题描述】:

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

#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 对象 之后,调用复制构造函数? 我说的对吗?

第一季度。定义析构函数。

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

对吗?

第二季度。定义复制构造函数。

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

第三季度。定义赋值运算符。

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

谢谢, 我会很感激的!

【问题讨论】:

  • 网络上确实有 数百万 个遵循三法则的示例对象实现。仅在这个网站上就有数千人。看到右边的“相关”列表了吗?尝试点击它。 vtc.
  • 如果需要,可能为Counts 分配空间并从a.Counts 复制。可能先删除旧的Counts(如果它太小)。
  • What is The Rule of Three? 的可能重复项
  • 还要记住零规则。通过使用已经实现这三个的资源管理类型(在本例中为std::vector&lt;int&gt;),您自己的类型将不再需要它们中的任何一个。

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


【解决方案1】:

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

第一季度。没错

第二季度。大概您打算将数组大小存储在size 中。例如

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

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

第三季度。我会查找copy and swap 成语。这使您可以使用复制构造函数编写赋值运算符。

【讨论】:

    猜你喜欢
    • 2011-06-09
    • 2012-06-27
    • 1970-01-01
    • 2011-05-19
    • 2017-01-16
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多