【发布时间】: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<int>),您自己的类型将不再需要它们中的任何一个。
标签: c++ destructor copy-constructor assignment-operator rule-of-three