三法则.复制构造函数,赋值操作符实现
Rule of Three. Copy Constructor, Assignment Operator Implementation
三原则。复制构造函数、赋值操作符实现
#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;
}
显然这需要有三个规则。你能帮我定义一下吗?
。
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?
}
第三季。定义赋值操作符
IntPart& IntPart::operator= (const IntPart& a)
{
if ( right != a)
{
// Anybody has any idea about how to implement this?
}
return *this;
}
谢谢,我很感激!
Q0。不,这只调用复制构造函数。这是一个相当大的误解,对象只构造一次。
Q1。这是正确的
Q2。假设您打算将数组大小存储在size
中。例如
IntPart::IntPart()
{
Counts = new int[101] (); // allocate all to 0s
numParts = 0;
size = 101; // save array size
}
如果不将数组大小存储在某个地方,则无法编写复制构造函数。
第三季。我会查找复制和交换习语。这允许您使用复制构造函数编写赋值操作符。
相关文章:
- 将赋值运算符实现为"destroy + construct"是否合法?
- 复制构造函数和赋值运算符实现选项 -
- c++中的重载赋值操作符
- c++类继承和赋值操作符
- 带引用类成员的赋值操作符
- 复制构造函数,赋值操作符重载
- c++派生类赋值操作符
- 通过调用Move赋值操作符实现Move构造函数
- 带有映射的赋值操作符
- 单参数构造函数和赋值操作符
- 如何从复制赋值操作符调用复制构造函数
- c++复制构造函数,重载赋值操作符,方法get()
- 用于具有const数据成员的类的move和右值赋值操作符
- 类赋值操作符和复制构造函数
- 赋值操作符重载
- 影响正确性的move构造函数/赋值操作符示例
- 三法则.复制构造函数,赋值操作符实现
- 移动构造函数和赋值操作符,使用复制-交换习惯实现
- 根据move构造函数实现复制赋值操作符
- 为什么我要将复制构造函数和赋值操作符设为私有并在c++中实现呢?