【问题标题】:Overloaded Constructors all display instead of just the targeted constructor [closed]重载的构造函数全部显示,而不仅仅是目标构造函数[关闭]
【发布时间】:2013-01-06 03:26:45
【问题描述】:

为什么在 main 中的对象使用 Add() 函数后 Print() 函数没有正确更新?

int main()
{
   Rational myRational(3,5);
   myRational.Print(); //Displays 3/5 as expected
   myRational.Add(2);
   myRational.Print(); //Displays 3/5 instead of 13/5
   return 0;
}

//from Rational.cpp

//Overloaded constructors
Rational::Rational() :
    num(0),
    denom(1)
{
}
Rational::Rational(int n) :
    num(n),
    denom(1)
{
}

Rational::Rational(int n, int d) :
    num(n),
    denom(d)
{
}

Rational Rational::Add(const Rational& r1) const
{
    int numerat = num * r1.getDenominator() +
                 denom * r1.getNumerator();
    int denomin = denom * r1.getDenominator();

    return Rational(numerat, denomin);
} 

void Rational::Print()
{
    cout << num << "/" << denom <<endl;
}

在调试代码时,Add 函数会按预期返回值 13 和 5,正确的构造函数也会返回值。不幸的是,Print() 函数保留了原始分数而不是新值。

【问题讨论】:

  • 现在您已经阅读了答案并意识到您被 (1) 错误命名(纯函数的命令式“命令”名称)和 (2) 误导糟糕的调用模式设计(成员函数而不是独立的operator+)。实际解决方案:定义一个名为operator+ 的独立函数。使其成为Rationalfriend,或者让它使用修改成员函数operator+=。一般来说,将纯函数命名为函数结果的描述是个好主意。例如sum,如果您不想使用operator+

标签: c++ oop reference constructor constructor-overloading


【解决方案1】:

因为方法Rational Rational::Add(const Rational&amp; r1) const,正如签名所暗示的那样,它的实现方式不会修改调用它的对象,而是创建一个新的Rational 实例并返回它。

尝试:

myRational.Print(); //Displays 3/5 as expected
myRational = myRational.Add(2);
myRational.Print(); //Displays 3/5 instead of 13/5

提示:签名末尾有 const 的事实意味着该方法不会修改调用它的实例的任何内容,这意味着该方法永远不会修改myRational 你调用它。

【讨论】:

    【解决方案2】:

    这个功能:

    Rational Rational::Add(const Rational& r1) const
    

    将结果返回到调用范围。您没有将结果存储在任何地方。因此,您将获得 myRational 原始值。

    尝试将值保存在对象中,然后打印。如果你也想保留myRational的原始内容,那么试试这个:

    int main()
    {
           Rational myRational(3,5);
           myRational.Print(); //Displays 3/5 as expected
           Rational myRational2 = myRational.Add(2); //Result stored in new object
           myRational2.Print(); //Printed new object values
           return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多