我最近发现,当我在一个类中有指针时,我需要指定一个 Copy 构造函数。
为了了解这一点,我编写了以下简单代码。它可以编译,但在执行复制构造函数时会出现运行时错误。
我试图从被复制对象的指针中复制值,但避免分配相同的地址。
那么,这里有什么问题?
class TRY{
public:
TRY();
~TRY();
TRY(TRY const &);
int *pointer;
void setPointer(int);
};
void TRY::setPointer(int a){
*pointer = a;
return;
}
TRY::TRY(){}
TRY::~TRY(){}
TRY::TRY(TRY const & copyTRY){
int a = *copyTRY.pointer;
*pointer = a;
}
int main(){
TRY a;
a.setPointer(5);
TRY b = a;
b.setPointer(8);
cout << "Address of object a = " << &a << endl;
cout << "Address of object b = " << &b << endl;
cout << "Address of a.pointer = " << a.pointer << endl;
cout << "Address of b.pointer = " << b.pointer << endl;
cout << "Value in a.pointer = " << *a.pointer << endl;
cout << "Value in b.pointer = " << *b.pointer << endl;
return 0;
}
我将把这个概念用于其他有很多指针的类,我需要将所有值从一个对象复制到另一个。此代码最初需要复制,所以我想保留复制的可能性(我不会将复制构造函数隐藏为私有(private))。
此外,我需要实现的真正类有大约 10 个指针,而且它可能会随着时间而改变。在 C++ 中有没有更聪明的方法来拥有一个深拷贝构造函数?...
最佳答案
使用语句 int* pointer
您刚刚定义了一个指针,但还没有分配任何内存。首先,您应该通过像这样分配一些内存来使其指向正确的内存位置:int* pointer = new int
。然后再次在复制构造函数中,您必须为复制的对象分配内存。另外,不要忘记在析构函数中使用 delete 来释放内存。
我希望这个例子有帮助:
class B
{
public:
B();
B(const B& b);
~B();
void setVal(int val);
private:
int* m_p;
};
B::B()
{
//Allocate the memory to hold an int
m_p = new int;
*m_p = 0;
}
B::B(const B& b)
{
//Allocate the memory first
m_p = new int;
//Then copy the value from the passed object
*m_p = *b.m_p;
}
B::~B()
{
//Release the memory allocated
delete m_p;
m_p = NULL;
}
void B::setVal(int val)
{
*m_p = val;
}
关于c++ - 使用指针复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/781760/