为什么运算符重载不正常?

时间:2015-09-01 12:40:43

标签: c++ operator-overloading

在C ++中重载operator ++时出现编译错误。这是代码:

#include <iostream>
using namespace std;

class Age{
    private:
        int age;
    public:
        Age(int age): age(age){

        }

        Age& operator++(){
            Age ages(this->age + 1);
            return ages;
        }

        int getAge(){
            return age;
        }
};


int main(){

    Age myAge(20);
    Age nextAge = myAge++;
    cout << nextAge.getAge() << endl;
    return 0;
}

我在哪里弄错了?

3 个答案:

答案 0 :(得分:8)

operator++()定义了预增量运算符。

要定义后期增量,您需要声明operator++(int)

int参数实际上并未使用,但需要有一些语法方法来区分预增量和后增量重载,因此它们具有不同的签名。

您还有其他问题:您的操作员没有修改*this它只修改了一个局部变量,并且它返回了对该局部变量的引用,当您尝试访问该局部变量时,这将导致未定义的行为返回值。

您可能希望定义一个修改*this并返回引用的预增量:

    Age& operator++(){
        this->age += 1;
        return *this;
    }

然后根据它定义后增量,创建副本并按值返回:

    Age operator++(int){
        Age age(*this);    // make a copy of the current value
        ++*this;           // update the current value
        return age;        // return the copy
    }

你也奇怪地使用它:

Age nextAge = myAge++;

nextAge变量将成为下一个年龄,它将是myAge的旧值,myAge将增加到下一个值。尝试更改您的程序以使用简单的int变量,并查看++运算符的行为。

如果您不了解运营商的行为,那么尝试创建自己的operator++重载毫无意义!

也许你真正想要的只是operator+所以你可以写:

Age nextAge = myAge + 1;

有几种方法可以定义operator+函数。给定上面的预增量运算符,您可以像这样定义一个非成员函数:

Age operator+(const Age& age, int n) {
    Age newAge(age);
    while (n--) {
        ++newAge;
    }
    return newAge;
}

或者更有效地作为(const)成员函数:

Age operator+(int n) const {
    Age newAge(*this);
    newAge->age += n;
    return newAge;
}

答案 1 :(得分:1)

您不应该在operator++重载中返回对局部变量的引用。这将导致未定义的行为。在这种情况下按价值返回。

答案 2 :(得分:0)

预增量运算符应如下所示:

Age& operator++()
{
    ++(this->age);
    return *this; // you can safely return a reference to the object pointed by "this"
}

后增量运算符应如下所示:

Age operator++(int) // the int argument is merely to distinguis the two operators - it has no other use
{
    Age previousAge( this->age ); // the post-increment operator must return the value before incementation
    ++(this->age);
    return previousAge; // you can safely return a copy of a local variable
}

此外,如果成员变量使用Hungarian notation,则不需要使用“this”。