【问题标题】:Do objects Coming into the Overloaded << Operator Function have to be Constants?进入重载 << 运算符函数的对象是否必须是常量?
【发布时间】:2016-03-22 06:18:22
【问题描述】:

我有一个我正在编写的类程序,我们正在重载运算符。除了插入操作符之外,我对任何其他操作都没有太多麻烦。传递的对象有一个字符数组,其中存储了字符。这些字符是代表数字的 ASCII 值,ACSII 值 1 代表 1。2 代表 2。我现在需要将 char 数组转换回相应的字符(1 = 49、2 = 50 等)通过将“0”添加到数组中的所有元素。我无法更改数组的内容,因为它的对象是作为常量传入的。我的问题是:

传入重载的插入运算符函数的对象是否必须作为常量传入?

我相当肯定我们的教授希望我们在这个函数中转换这个数组。我们之前编写了整个程序,但使用了 read() 和 write() 函数,而不是重载插入和提取运算符。我们在 read 和 write 函数中进行了转换,他提到在这个赋值中使用相同的代码进行前面的赋值,但使用重载的运算符。我能够在之前的赋值中转换数组中的数字,因为它不是一个常数。代码如下:

ostream & operator<< (ostream &Out, const MyFloat & x)
{
    int Counter=0;
    int PrintDigits=0;

    //FIGURE OUT HOW TO CONVERT BACK IN THIS FUNCTION

    for (int h=0; h<=MyFloat::MAXDIGIT-1; h++)//converts from number to character
    {
        x.Number[h] += '0';//ISSUE is here, can't change this b/c it's const
    }

    Out << "0.";

    for (int i=x.MAXDIGIT-1; i>=0 && x.Number[i] == '0'; --i)//counting right to left, until we reach the first non-zero number, this is used to print out the correct amount of numbers, to keep from printing trailing 0s
    {
        ++Counter;
    }

    PrintDigits = 19 - Counter;

    for (int j=0; j<=PrintDigits; ++j)
    {
        Out << x.Number[j];
    }

    return Out;
}

【问题讨论】:

  • operator&lt;&lt; 不应该修改它的 RHS 操作数,所以如果你需要传递非常量,你可能有设计问题。
  • 简单的回答:是的,您可以删除常量。但是你不应该。
  • 找到一种无需修改即可打印数字的方法。
  • “ISSUE 在这里,不能改变这个 b/c 它是 const”应该改为“ISSUE 在这里,我不应该改变这个const

标签: c++ overloading constants operator-keyword insertion


【解决方案1】:

我想通了。我没有尝试更改传入的 const 对象,而是将其转换为存储在 ostream 变量 Out 中。

ostream & operator<< (ostream &Out, const MyFloat & x)
{
    int Counter=0;
    int PrintDigits=0;

    Out << "0.";

    if (x.NumberOfDigits != '0')
    {
        for (int i=x.MAXDIGIT-1; i>=0 && x.Number[i] == 0; --i)//counting right to left, until we reach the first non-zero number, this is used to print out the correct amount of numbers, to keep from printing trailing 0s
        {
            ++Counter;
        }

        PrintDigits = 19 - Counter;

        for (int j=0; j<=PrintDigits; ++j)
        {
            Out << (int) x.Number[j];
        }
    }

    else
        Out << "?";

    return Out;
}

正如我所说,这不是我的选择,只是任务要求我做的事情。

【讨论】:

    猜你喜欢
    • 2011-09-16
    • 2017-07-20
    • 2019-02-09
    • 1970-01-01
    • 2012-10-02
    • 2012-12-10
    • 1970-01-01
    • 2013-11-17
    • 1970-01-01
    相关资源
    最近更新 更多