什么是复制构造函数?

时间:2015-02-20 21:27:04

标签: c++

让我们说这是我的代码

class Rational
{
    public:
        Rational (Rational &copyObject);
        Rational add (Rational rhs);
    private:
        int mNum;
        int mDen;
};
Rational :: Rational (Rational &copyObject)
{
    this->mNum = copyObject.mNum;
    this->mDen = copyObject.mDen;
}
Rational Rational:: add (Rattional rhs)
{
    this->mNumerator = (this->mNumerator * rhs.mDenominator) + 
                       (rhs.mNumerator * this->mDenominator);

    this->mDenominator = this->mDenominator * rhs.mDenominator;

    return *this;
}

int main (void)
{
    Rational r1(10,3), r2 (20,3) //let just assume I have a constructor for initialize
    r1.add(r2);
}

我不太清楚Rational :: Rational (Rational &copyObject)做什么 这是否意味着如果我没有这个功能,我会复制r2,如果我有这个功能,我会将Rational Rational:: add (Rattional rhs)中的局部变量连接到main()中的r2?

还有一件事,编译器如何知道何时调用该函数?

我是c ++的新手,请尽可能简单地解释 谢谢!

1 个答案:

答案 0 :(得分:0)

它是一个构造函数,它接受Rational并复制它(与你假设的构造函数不同,它需要2个整数)。因此,例如,您可以Rational r3(r2);复制r2