简体   繁体   English

在 C++ 中重载方法时,是否可以考虑相等运算符并将返回值分配给另一个 class 实例?

[英]When overloading methods in C++, is it possible to consider the equal operator and assign the return value to another class instance?

Is it possible to have in a class a method that modifies its own class instance, but by overloading it can also modify another class instance or even create a new one, if for example the equal sign is used?是否可以在 class 中使用一种方法来修改其自己的 class 实例,但通过重载它还可以修改另一个 class 实例,甚至创建一个新实例,例如使用等号? Or do I need to overload the operator in a special way?还是我需要以特殊方式重载运算符?

Something like this:像这样的东西:

class MyClass{
public:
    MyClass() {};
    MyClass(int x): number(x) {};

    void increaseNumber(){
        number++;
    }

    MyClass increaseNumber() const{
        MyClass tempObj(this->number);
        tempObj.number++
        return tempObj;
    }
private:
    int number = 0;
}


int main(){
    MyClass a(10);
    
    a.increaseNumber();             // -> a.number == 11
    MyClass b = a.increaseNumber()  // -> b.number == 12   ???
}

First I hope I understood your question correctly, please correct me if you don't mean this.首先,我希望我正确理解了您的问题,如果您不是这个意思,请纠正我。 The overload can be done as long as the signature is changed.只要更改签名,就可以完成重载。 in your code the signature is changed by const key word, also return type.在您的代码中,签名由 const 关键字更改,也返回类型。 I can give you an example of overloading equal sign twice in the same class as follow:我可以给你一个在同一个 class 中重载等号两次的例子,如下所示:

the first implementation is used as default copy, you copy the rhs to the lhs, while the second implementation move the data without copying.第一个实现用作默认副本,您将 rhs 复制到 lhs,而第二个实现移动数据而不复制。

class Factor {
    int _n = 0;
    int _d = 1;        
    
public:
    Factor & operator = (const Factor &);
    Factor & operator = (Factor &&) noexcept;

Factor & Factor::operator = ( const Factor & rhs ) {
    message("op =");
    if( this != &rhs ) {
        _n = rhs.numerator();
        _d = rhs.denominator();
    }
    return *this;
}

Factor & Factor::operator = ( Factor && rhs ) noexcept {
    message("op move =");
    if ( this != &rhs ) {
        _n = std::move(rhs._n);
        _d = std::move(rhs._d);
        rhs.reset();
    }
    return *this;
}

As a conclusion for me and as an answer to my own question:作为对我的结论和对我自己问题的回答:

  1. You cannot overload a method by changing the return type but keeping the same parameters.您不能通过更改返回类型但保持相同的参数来重载方法。 So for this purpose you have to define a method with a different name.因此,为此您必须定义一个具有不同名称的方法。

  2. If a class instance is initialized with another already existing class instance and the equal sign, the (copy?) constructor is called and not the assignment operator.如果使用另一个已经存在的 class 实例和等号初始化 class 实例,则调用(复制?)构造函数而不是赋值运算符。 eg:例如:

 MyClass a(10); MyClass b = a;

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

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