<分区>
我正在尝试实现一个原型(prototype)模式。当我使用 *this
传递 self 对象以便使用复制构造函数克隆自身时,由于以下原因,我无法访问 self 成员函数:
错误:将“const ConcreteClonable1”作为“this”参数传递会丢弃限定符 [-fpermissive]
该错误与 const
的错误使用有关。但是,如果我从复制构造函数中删除 const
一切正常。我想按预期使用复制构造函数,使用 const
参数,并能够访问非常量类成员。
代码如下:
/* Prototype base class. */
class Prototype
{
protected:
std::string type;
int value;
public:
virtual Prototype* clone() = 0;
std::string getType() { return type; }
int getValue() { return value; }
};
//clonable class
class ConcreteClonable1 : public Prototype
{
public:
ConcreteClonable1(int number)
{
std::cout << "ConcreteClonable1 cnstr\n";
type = "Type1";
value = number;
}
//compilation error if const is used
ConcreteClonable1 (const ConcreteClonable1& x)
{
std::cout << "ConcreteClonable1 copy cnstr\n";
type = x.getType();
value = x.getValue();
}
Prototype* clone() { return new ConcreteClonable1(*this); }
};
对象在 Factory
中初始化。
问题是为什么会这样?有没有更好的方法来使用某种 copy来自 C++ STL 的函数?