我遇到过一些C ++代码。为什么我们必须在块中使用* this而不是这个?

时间:2017-06-14 14:15:51

标签: c++ this this-pointer

我有以下代码,我想知道为什么它使用*this代替this

class Quotation
{
protected:
    int value;
    char* type;
public:
    virtual Quotation* clone()=0;

    char * getType()
    {
        return type;
    }

    int getValue()
    {
        return value;
    }
};


class bikeQuotation : public Quotation
{
public:
    bikeQuotation(int number)
    {
        value=number;
        type="BIKE";
    }

    Quotation * clone()
    {
        return new bikeQuotation(*this);  // <-- Here!
    }
};

1 个答案:

答案 0 :(得分:4)

this是对象的指针。复制构造函数需要引用到对象。将指针转换为引用的方式是使用解引用*运算符。

相关问题