简体   繁体   English

在C ++中,如何在不通过参数传递对象的情况下重载运算符?

[英]in C++, How can I overload an operator without passing an object through the parameters?

For example, I'd like the following to output the number 6, but every example I've ever seen of operator overloading contains a "const" object in the parameters. 例如,我希望以下输出数字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;
}

Here is the code that does what you want: 这是执行您想要的代码:

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;
}

Your code had a number of compiler errors that have also been fixed. 您的代码有许多编译器错误,这些错误也已修复。 For instance, Class should be class and Main should be main. 例如,Class应该是class,Main应该是main。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM