c++ - 在复制构造函数中使用 *this 作为 const 来克隆自身

标签 c++ constants clone copy-constructor

<分区>

我正在尝试实现一个原型(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 的函数?

最佳答案

只委托(delegate)Prototype的复制构造

ConcreteClonable1::ConcreteClonable1(const ConcreteClonable1 & x) : Prototype(x) 
{ std::cout << "ConcreteClonable1 copy cnstr\n"; }

一般来说,你应该更喜欢成员初始化而不是在构造函数的主体中赋值。

Prototype::Prototype(std::string type_, int value_) : type(type_), value(value_) {}

ConcreteClonable1::ConcreteClonable1(int number) : Prototype("Type1", number) 
{ std::cout << "ConcreteClonable1 cnstr\n"; }

关于c++ - 在复制构造函数中使用 *this 作为 const 来克隆自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48663884/

相关文章:

c++ - Microsoft::VisualStudio::CppUnitTestFramework 中的参数化测试方法

c# - C# 中的不可变本地值 - 一个特定的用例

c++ - 为什么 `const` 会作用于它之前的那个东西?

c - 功能正常,没有 "const"标志。 "const"的重要性?

c++ - 局部静态变量被多次实例化,为什么?

C++ LNK1120 和 LNK2019 错误 : "unresolved external symbol WinMain@16"

java - 实现克隆功能

c# - 克隆任意对象的函数

rust - 派生特征会导致意外的编译器错误,但手动实现有效

c++ - 用几个 IF 条件编码或者 SWITCH-CASE 在这里可能很好?