C++ 复制的对象更改其用于复制的基类指针的属性
考虑以下类别:C++ 复制的对象更改其用于复制的基类指针的属性,c++,inheritance,polymorphism,clone,deep-copy,C++,Inheritance,Polymorphism,Clone,Deep Copy,考虑以下类别: class Base { public: ... // include virtual destructor and rest of methods virtual void changeField(int val) = 0; virtual Base * clone() const = 0; }; class Derived: public Base { int x; public: ... // include i
class Base {
public:
... // include virtual destructor and rest of methods
virtual void changeField(int val) = 0;
virtual Base * clone() const = 0;
};
class Derived: public Base {
int x;
public:
... // include its destructor and rest of its methods
void changeField(int val) { x = val; }
Derived * clone() const { return new Derived(*this); }
};
假设我有一个现有的Base*
指针bp
,它指向一个派生的
对象。然后我调用bp->clone()
进行复制,并将结果对象的指针存储在Base*
指针,copypoter
中
当我尝试在copyPointer
上changeField
时,值已更改,但原始对象的字段也已更改。为什么会这样?我能做些什么来防止这种情况?我必须从头开始创建一个全新的对象吗
编辑:这里是我的主要功能,我在其中实现了所描述的场景
int main() {
try {
Base * copyPointer = bp->clone();
copyPointer->changeField(5);
cout << copyPointer->print() << endl; //prints the field of Derived
delete copyPointer;
}
catch (exception& e) { // I also have an Exception class in my code
cout << e.what() << endl;
}
}
intmain(){
试一试{
Base*copyPointer=bp->clone();
copyPointer->changeField(5);
cout print()您认为copyPointer
上的函数changeField()
更改原始对象的假设是错误的
我详细阐述了你的例子:
#include <iostream>
using std::cout;
using std::endl;
class Base {
public:
// include virtual destructor and rest of methods
virtual void changeField(int val) = 0;
virtual Base * clone() const = 0;
virtual int print() const =0;
};
class Derived: public Base {
int x;
public:
// include its destructor and rest of its methods
Derived(int i):x(i) {}
void changeField(int val) { x = val; }
Derived * clone() const { return new Derived(*this); }
int print()const { return x; }
};
int main() {
Base* bp =new Derived(3);
cout <<bp->print() <<endl;
Base * copyPointer = bp->clone();
copyPointer->changeField(5);
cout <<copyPointer->print() <<endl; //prints the field of Derived
cout <<bp->print() <<endl;
}
显示显示您描述的行为的代码。不描述,请发布一个。用一个示例更新您不显示changeField
或您的复制构造函数。是什么让您认为它们是无错误的?如果我没有实现复制构造函数,会不会调用默认构造函数?值得建议的是:使用关键字override
在派生类中
3
5
3