【发布时间】:2015-11-06 02:43:11
【问题描述】:
我正在尝试为 C++ 实现 BigInt,但遇到了复制构造函数的问题。你可以看到我注释掉了复制构造函数的原始代码,它只是*this = orig;。但我发现你需要使用指针来代替。我不完全确定这完全是如何工作的,但是目前代码没有正确地创建一个复制构造函数。
-BigIntVector 是一个自定义向量类。与 STL 向量比较。
BigInt.h:
class BigInt {
private:
BigIntVector bigIntVector;
bool isPositive;
int base;
unsigned int skip;
BigIntVector* ptr; //pointer to copy?
public:
// copy constructor
BigInt(BigInt const& orig);
// constructor where data value is passed as a long
BigInt(long num);
// destructor
~BigInt();
// binary '+' operator
BigInt operator+(BigInt const& other) const;
// unary '+' operator
BigInt operator+() const;
//more operator unloading functions
这是我当前在 BigInt.cpp 中的构造函数实现:
// copy constructor
BigInt::BigInt(BigInt const& orig) {
ptr = new BigIntVector;
*ptr = *orig.ptr;
//*this = orig;
}
// constructor where operand is a long
BigInt::BigInt(long num) {
//this->data = num;
ptr = new BigIntVector;
base = 10;
int sizeOfLong = 0; //holds size of num
int tempNum = num;
//get size of num
if (tempNum == 0) {
sizeOfLong = 1;
}
while (tempNum != 0)
{
tempNum /= 10;
++sizeOfLong;
}
//resize vector to match size of long
bigIntVector = BigIntVector(sizeOfLong);
if (num < 0) {
isPositive = false;
num *= -1;
}
else {
isPositive = true;
}
long pushedNum;
//cout << "num: " << num << endl;
for (int i = sizeOfLong - 1; i >= 0; --i) {
pushedNum = (long)(num%base);
bigIntVector.setElementAt(i, pushedNum);
num /= base;
}
}
// destructor
BigInt::~BigInt() {
//delete *this;
}
//code for overloading operators for BigInt below
BigIntVector 构造函数的代码:
BigIntVector::BigIntVector(long initialSize)
{
vectorTotalSize = initialSize;
vectorIncrementSize = initialSize;
vectorArray = (long *)malloc(initialSize*sizeof(long));
for (long i = 0; i < initialSize; i++) vectorArray[i] = 0;
nextValue = 0;
}
【问题讨论】:
-
*this = orig;无论如何都不是实现复制构造函数的正确方法。赋值运算符应该利用复制构造函数,而不是相反。 -
更新:“-BigIntVector 是一个自定义向量类。与 STL Vector 比较。”
-
类定义中的
BigIntVector* ptr;是什么?您的构造函数使其指向new向量,但随后没有在这个新向量中放入任何内容。 -
除特殊情况外,不要
new数据结构对象本身,如ptr = new BigIntVector。而是让他们成为正式成员。您可能会发现默认生成的复制构造函数和赋值运算符会自动为您工作。 -
我认为这是成为 Java 大用户的副作用。 “正式成员”的正确语法是什么
标签: c++ pointers constructor copy-constructor biginteger