简体   繁体   中英

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? 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. I can give you an example of overloading equal sign twice in the same class as follow:

the first implementation is used as default copy, you copy the rhs to the lhs, while the second implementation move the data without copying.

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. eg:

 MyClass a(10); MyClass b = a;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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