无法弄清楚为什么使用重载比较运算符会在执行前调用复制构造函数

Cant figure out why using overloaded comparison operator is calling a copy constructor before execution

作为我的编程作业 class,我正在为浮点数和动态内存分配编写 class 定义。我们将构建一个 class 并使用运行它的测试驱动程序主程序并告诉我们代码是否正常工作。我的 class 代码远未完成,但这个问题让我发疯,我无法弄清楚。每当重载的 == 运算符被调用时,我的复制构造函数也会被调用。我的最后一个 post,我收到了很多关于 post 代码太长的负面评论,所以我尽我所能只 post 查看问题所需的代码。

这是我的规格:

#include <iostream>
#include <ctype.h>

using namespace std;

class MyFloat
{
    enum {DefaultSizeTen=10};
    char *Number;

    int NumberOfDigits;
    int MaxNumberOfDigits;

public:

    ~MyFloat();//destructor

    MyFloat(const MyFloat & RHS);
    MyFloat();      //default constructor
    MyFloat(unsigned int Input); //create any length of MyFloat

    int Digits();
    int MaxDigits();

    MyFloat operator= (const char Input[]);


    int operator== (MyFloat x);

    MyFloat operator+ (MyFloat x);
    int operator> (MyFloat x);
    int operator< (MyFloat x);

    friend ostream& operator<< (ostream &Out, const MyFloat & X);
    friend istream& operator>> (istream &In, MyFloat & X);

};

在测试驱动程序中,这是使用重载 == 运算符的函数:

void TestComparison()
{
    MyFloat A, B, Sum;


    cout << "\n\n== == == == ==  Testing \"== \" for MyFloat  == == == == == \n\n";

    cout << "MyFloat variables have maximum length of " << A.MaxDigits() << endl;
    do
    {
        cout << "\nEnter A  ==> ";
        cin  >> A;
        cout << "\nEnter B  ==> ";
        cin  >>  B;

        cout << "\n (A == B) is " << ((A == B) ? "TRUE " : "FALSE ") << endl;


    }
    while ( SpaceBarToContinue() );
}

我在这条线上 cout << "\n (A == B) is " << ((A == B) ? "TRUE " : "FALSE ") << ends; 遇到了问题。在调用重载的比较运算符之前,RHS 与另一个变量一起被发送到复制构造函数中,我不知道它来自哪里(作为 *this 进入复制构造函数)。这是复制构造函数:

MyFloat::MyFloat(const MyFloat & RHS)
{
    MaxNumberOfDigits=RHS.MaxNumberOfDigits;
    NumberOfDigits=RHS.NumberOfDigits;

    Number = new (nothrow) char[RHS.NumberOfDigits+1]; //+1 for overflow

    if (Number != NULL)
    {
        for (int i=0; i<=RHS.NumberOfDigits-1; ++i)
        {
            Number[i]=RHS.Number[i];
        }
    }

    else
        NumberOfDigits=0;
}

我不知道这些信息是否足够,但我收到了一些负面反馈,因为上次 post 代码太长了,所以我把它删减了很多。

Cant figure out why using overloaded comparison operator is calling a copy constructor before execution

您正在按值传递参数。

int operator== (MyFloat x);

将其更改为更惯用的形式:

  1. 将 return 类型更改为 bool
  2. 使参数成为 const&.
  3. 使成员函数成为const成员函数。

bool operator==(MyFloat const& x) const;