繁体   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?

是否可以在 class 中使用一种方法来修改其自己的 class 实例,但通过重载它还可以修改另一个 class 实例,甚至创建一个新实例,例如使用等号? 还是我需要以特殊方式重载运算符?

像这样的东西:

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

首先,我希望我正确理解了您的问题,如果您不是这个意思,请纠正我。 只要更改签名,就可以完成重载。 在您的代码中,签名由 const 关键字更改,也返回类型。 我可以给你一个在同一个 class 中重载等号两次的例子,如下所示:

第一个实现用作默认副本,您将 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;
}

作为对我的结论和对我自己问题的回答:

  1. 您不能通过更改返回类型但保持相同的参数来重载方法。 因此,为此您必须定义一个具有不同名称的方法。

  2. 如果使用另一个已经存在的 class 实例和等号初始化 class 实例,则调用(复制?)构造函数而不是赋值运算符。 例如:

 MyClass a(10); MyClass b = a;

暂无
暂无

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

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