我在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;
}
Run Code Online (Sandbox Code Playgroud)
我哪里弄错了?
operator++() 定义预增量运算符.
要定义后增量,您需要声明 operator++(int)
该int参数实际上并未使用,但需要一些语法方法来区分预增量和后增量重载,因此它们具有不同的签名.
但是您有其他问题:您的运算符不修改*this它只修改局部变量,并返回对该局部的引用,当您尝试访问返回值时将导致未定义的行为.
您可能希望定义一个修改*this并返回引用的预增量:
Age& operator++(){
this->age += 1;
return *this;
}
Run Code Online (Sandbox Code Playgroud)
然后根据它定义后增量,创建副本并按值返回:
Age operator++(int){
Age age(*this); // make a copy of the current value
++*this; // update the current value
return age; // return the copy
}
Run Code Online (Sandbox Code Playgroud)
你也奇怪地使用它:
Age nextAge = myAge++;
Run Code Online (Sandbox Code Playgroud)
该nextAge变量会不会成为下一个时代,这将是旧值myAge,并且myAge将递增到下一个值.尝试更改程序以使用简单int变量并查看++操作符的行为方式.
operator++如果您不了解操作员的操作,那么尝试创建自己的重载是没有意义的!
也许你真正想要的只是operator+这样你可以写:
Age nextAge = myAge + 1;
Run Code Online (Sandbox Code Playgroud)
有几种方法可以定义该operator+功能.给定上面的预增量运算符,您可以像这样定义一个非成员函数:
Age operator+(const Age& age, int n) {
Age newAge(age);
while (n--) {
++newAge;
}
return newAge;
}
Run Code Online (Sandbox Code Playgroud)
或者作为(const)成员函数更有效:
Age operator+(int n) const {
Age newAge(*this);
newAge->age += n;
return newAge;
}
Run Code Online (Sandbox Code Playgroud)