-1

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

#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; } 

它正确吗? Q2302。定义复制构造函数。

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; 
} 

谢谢, 我将不胜感激!

+3

字面上有数百万*样本对象实现遵循网络上的三规则。数千在这个站点单独。看到右边的“相关”列表?尝试点击它。 VTC。 – WhozCraig 2013-04-23 06:39:21

+0

如果需要可能为'​​Counts'分配空间,并从'a.Counts'复制。可能首先删除旧的“Counts”(如果它太小)。 – 2013-04-23 06:42:01

+0

可能重复[三条法则是什么?](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-ree) – 2013-04-23 07:23:51

回答

3

Q0。不,这只会调用复制构造函数。这是一个相当大的误解,对象有史以来只有

Q1。这是正确的

Q2。大概你打算在size中存储阵列大小。例如。

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

如果没有存储数组大小的地方,你的拷贝构造函数将是不可能写。

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

相关问题