【问题标题】:in C++, How can I overload an operator without passing an object through the parameters?在 C++ 中,如何在不通过参数传递对象的情况下重载运算符?
【发布时间】:2014-05-11 01:40:12
【问题描述】:

例如,我希望以下输出数字 6,但我见过的每个运算符重载示例都在参数中包含一个“const”对象。

Class MyClass
{
    private:
        int num;
    public:
        //Setter
        void setNum(int x)            {num = x;}

        //Getter
        int getNum()                  {return x;}

        //Overloading + Operator
        MyClass operator + (int add)
        {
        }
};

int Main()
{
    MyClass test;
    test.setNum(2);
    test = test + 4;
    cout << test.getNum();
    return 0;
}

【问题讨论】:

  • 参数中没有对象的运算符将是否定运算符或函数运算符,我认为您的问题措辞不正确。
  • 您的代码很好,但实际上您必须将一些代码放入operator+ 函数中。你确实通过参数传递了add。二进制 + 运算符必须有两个参数,这是无法绕过的。
  • 这个问题很混乱。让您的代码输出 6const 运算符没有矛盾:MyClass operator+(int add) const { MyClass x = *this; x.num += add; return x; }

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


【解决方案1】:

这是你想要的代码:

class MyClass
{
    private:
        int num;
    public:
        //Setter
        void setNum(int x)            {num = x;}

        //Getter
        int getNum()                  {return num;}

        //Overloading + Operator
        MyClass operator + (int add)
        {
            MyClass copy;
            copy.num = num + add;
            return copy;
        }
};

int main()
{
    MyClass test;
    test.setNum(2);
    test = test + 4;
    std::cout << test.getNum();
    return 0;
}

您的代码存在许多编译器错误,这些错误也已得到修复。例如,Class 应该是 class,Main 应该是 main。

【讨论】:

  • operator+ 不应该修改类,它应该返回一个独立于类的新值。 operator+= 会修改类。
猜你喜欢
  • 1970-01-01
  • 2020-09-11
  • 1970-01-01
  • 2020-07-25
  • 1970-01-01
  • 2011-08-30
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多