c++ - 存在重载 C++ 运算符的问题

标签 c++ overloading operator-keyword

我在理解这个概念时遇到一些问题。在main.cpp文件中,我们有一个函数如下:

void TestComparison()
{
    MyFloat X, Y;

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

    do
    {
        cout << "\nEnter X  ==> ";
        X.Read();
        cin.ignore(1000, '\n');             //  Discard all chars in input stream.
        cout << "\nEnter Y  ==> ";
        Y.Read();
        cin.ignore(1000, '\n');             //  Discard all chars in input stream.

        cout << "\n\n";

        if ( X == Y )
        {
            X.Write(); cout << " is equal to "; Y.Write();
        }
        else
        {
            X.Write(); cout << " is NOT equal to "; Y.Write();
        }
    }
    while ( SpaceBarToContinue() );
}

这是我正在写的类(class):

class MyFloat
{
    enum {MAXDIGIT=20};
    char Number[MAXDIGIT+1];
    char NumberOfDigits;

public:

    friend void AssignValue(MyFloat& X);//remove after the program works

    MyFloat();

    int Digits();
    int MaxDigits();
    void Read();
    void Write();

    MyFloat operator + (MyFloat x);
    int operator== (MyFloat x);
};

这是我的 == 重载函数 stub :

int MyFloat::operator== (MyFloat x)
{
    int Flag=0;

    return 1;
}

这样做的唯一目的是比较两个对象数组 X 和 Y。它们被传递到 == 重载函数中。我应该编写比较它们的算法。我知道如何编写比较这两个字符数组的算法,这不是问题,但我无法理解 X 和 Y 如何进入重载函数来比较它们?在main中,代码( X == Y )用于获取0或1。X和Y是如何传递到函数中的?

例如,我假设我的函数 stub 需要用 2 个参数重写:

int MyFloat::operator== (MyFloat x, MyFloat y)
{
    int Flag=0;

    return 1;
}

但是这样做会在 ( X == Y ) 的函数调用期间在主程序中产生一个错误,指出“重载“operator==”必须是二元运算符(有 3 个参数) '

所以我完全困惑如何将 MyFloat 的两个对象放入函数中进行比较。我对编程还很陌生(学习了 5-6 个月),非常感谢任何简单明了的答案。

最佳答案

当你写下:

if(a == b)

它的真正含义是:

if(a.operator==(b))

所以在你的方法中:

bool MyFloat::operator==(const MyFloat &x) const
{
    // x is b in call above
    // (*this) is a in call above

    // Your class invariant should guarantee this:
    // assert(x.NumberOfDigits < MAX_DIGITS);

    // In the scope of your class' methods:
    //   NumberOfDigits corresponds to this->NumberOfDigits
    //   Number corresponds to this->Number
    if(x.NumberOfDigits != NumberOfDigits) return false;
    // Same as: if(x.NumberOfDigits != this->NumberOfDigits) return false;
    return strncmp(x.Number, Number, NumberOfDigits) == 0;
    // Same as: return strncmp(x.Number, this->Number, this->NumberOfDigits) == 0;
}

请注意,我更改了您的方法的签名。正确的签名返回一个 bool 并采用一个 const (因为您不想更改参数)引用(避免复制大对象)作为参数。该方法是(并且必须是)const,因为它不应该修改对象,并且必须可以在 const 对象上调用。

请注意,可以使用以下签名将运算符定义为非成员函数(即类外部):

bool operator==(const MyFloat &a, const MyFloat &b)

关于c++ - 存在重载 C++ 运算符的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35784528/

相关文章:

Javascript:变量名中的冒号运算符是什么?

c++ - C++ 示例中的新运算符重载

java - result = result + (char)(c ^ d) 的作用是什么?

c++ - 将 XCTest 单元测试添加到现有应用程序不起作用

C++矩阵类模板

c++ - 是 T Min(T, T);总是比 const T& Min(const T&, const T&) 好;如果 sizeof(T) <= sizeof(void*)?

C# 函数引用重载方法

c# - 重载解析选择不兼容的泛型方法而不是兼容的基类方法

C++智能线性容器

c++ - C++ 结构中的数组